R Program to find Sum, Mean and Product of a Vector, ignore element like NA or NaN

How to find Sum, Mean and Product of a Vector, ignore elements like NA or NaN

Here we are explaining how to write an R program to find Sum, Mean, and Product of a Vector, ignore elements like NA or NaN. Here we are using built-in functions sum, mean, prod for this calculation. The numbers are passed to these functions directly here. The function sum() returns the sum of all the values present in its arguments. The sum of the values dividing with the number of values in a data series is calculated using the mean() function. Finally, the prod() is for finding the product of iven arguments.

sum(…, na.rm = FALSE)
mean(x, …)
prod(…, na.rm = FALSE)
 

In the above function argument structure by making na.rm = TRUE we can avoid the elements like NA, NAN.

How to find Sum, Mean and Product of a Vector, by ignoring NA using R Program

Given below are the steps which are used in the R program to find the sum, mean, and product of the vector values. In this R program, we directly give the values to built-in functions. Consider variable A for assigning vector value. And call each function by giving A as an argument. Make sure na.rm should be true as like na.rm = TRUE. Finally, print the function result.

ALGORITHM

STEP 1: Use the built-in functions

STEP 2: call sum() with vector and na.rm = TRUE as argument

STEP 3: call mean() with vector and na.rm = TRUE as argument

STEP 4: call prod() with vector and na.rm = TRUE as argument

STEP 5: print the result of each function

R Source Code

                                          A = c(30, NULL, 40, 20, NA)
print("Sum is:")
#ignore NA and NaN values
print(sum(A, na.rm=TRUE))
print("Mean is:")
print(mean(A, na.rm=TRUE))  
print("Product is:")
print(prod(A, na.rm=TRUE))
                                      

OUTPUT

[1] "Sum is:"
[1] 90
[1] "Mean is:"
[1] 30
[1] "Product is:"
[1] 24000