Calculate Sum, Mean, and Product of a Vector in R ignoring NA or NaN
Write a R program to find Sum, Mean and Product of a Vector, ignore element like NA or NaN.
Sample Solution :
R Programming Code :
# Create a numeric vector 'x' with elements 10, NULL, 20, 30, and NA
x = c(10, NULL, 20, 30, NA)
# Print a message indicating the calculation of the sum
print("Sum:")
# Calculate and print the sum of the elements in vector 'x', ignoring NA and NaN values
print(sum(x, na.rm=TRUE))
# Print a message indicating the calculation of the mean
print("Mean:")
# Calculate and print the mean of the elements in vector 'x', ignoring NA and NaN values
print(mean(x, na.rm=TRUE))
# Print a message indicating the calculation of the product
print("Product:")
# Calculate and print the product of the elements in vector 'x', ignoring NA and NaN values
print(prod(x, na.rm=TRUE))
Output:
[1] "Sum:" [1] 60 [1] "Mean:" [1] 20 [1] "Product:" [1] 6000
Explanation:
- x = c(10, NULL, 20, 30, NA): Creates a numeric vector x with elements 10, NULL (which is ignored), 20, 30, and NA (which represents a missing value).
- print("Sum:"): Prints the label "Sum:" to indicate that the following output will show the sum of the vector elements.
- print(sum(x, na.rm=TRUE)): Calculates and prints the sum of the elements in vector x, ignoring NA and NULL values, resulting in 60.
- print("Mean:"): Prints the label "Mean:" to indicate that the following output will show the mean of the vector elements.
- print(mean(x, na.rm=TRUE)): Calculates and prints the mean of the elements in vector x, ignoring NA and NULL values, resulting in 20.
- print("Product:"): Prints the label "Product:" to indicate that the following output will show the product of the vector elements.
- print(prod(x, na.rm=TRUE)): Calculates and prints the product of the elements in vector x, ignoring NA and NULL values, resulting in 6000.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to find Sum, Mean and Product of a Vector.
Next: Write a R program to find the minimum and the maximum of a Vector.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics