Compute Sum, Mean, and Product of Vector elements in R
Write a R program to compute sum, mean and product of a given vector elements.
Sample Solution :
R Programming Code :
# Create a vector 'nums' with numeric elements
nums = c(10, 20, 30)
# Print a message indicating the original vector
print('Original vector:')
# Print the original vector
print(nums)
# Print the sum of the vector elements
print(paste("Sum of vector elements:", sum(nums)))
# Print the mean (average) of the vector elements
print(paste("Mean of vector elements:", mean(nums)))
# Print the product of the vector elements
print(paste("Product of vector elements:", prod(nums)))
Output:
[1] "Original vector:" [1] 10 20 30 [1] "Sum of vector elements: 60" [1] "Mean of vector elements: 20" [1] "Product of vector elements: 6000"
Explanation:
- nums = c(10, 20, 30): Creates a vector nums with elements 10, 20, and 30.
- print('Original vector:'): Prints the label 'Original vector:' to the console.
- print(nums): Displays the contents of the nums vector.
- print(paste("Sum of vector elements:", sum(nums))): Calculates the sum of the elements in nums and prints the result with a label.
- print(paste("Mean of vector elements:", mean(nums))): Calculates the mean (average) of the elements in nums and prints the result with a label.
- print(paste("Product of vector elements:", prod(nums))): Calculates the product of the elements in nums and prints the result with a label.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to create bell curve of a random normal distribution.
Next: Write a R program to create a list of heterogeneous data, which include character, numeric and logical vectors. Print the lists.
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