w3resource

Find Sum, Mean, and Product of a Vector in R Programming

R Programming: Vector Exercise-6 with Solution

Write a R program to find Sum, Mean and Product of a Vector.

Sample Solution :

R Programming Code :

# Create a numeric vector 'x' with elements 10, 20, and 30
x = c(10, 20, 30)

# Print a message indicating the calculation of the sum
print("Sum:")

# Calculate and print the sum of the elements in vector 'x'
print(sum(x))

# Print a message indicating the calculation of the mean
print("Mean:")

# Calculate and print the mean of the elements in vector 'x'
print(mean(x))  

# Print a message indicating the calculation of the product
print("Product:")

# Calculate and print the product of the elements in vector 'x'
print(prod(x))

Output:

[1] "Sum:"
[1] 60
[1] "Mean:"
[1] 20
[1] "Product:"
[1] 6000                         

Explanation:

  • x = c(10, 20, 30): Creates a numeric vector x with the elements 10, 20, and 30.
  • print("Sum:"): Prints the label "Sum:" to the console to indicate the following output is the sum of the vector elements.
  • print(sum(x)): Calculates and prints the sum of the elements in vector x, which is 60.
  • print("Mean:"): Prints the label "Mean:" to the console to indicate the following output is the mean of the vector elements.
  • print(mean(x)): Calculates and prints the mean of the elements in vector x, which is 20.
  • print("Product:"): Prints the label "Product:" to the console to indicate the following output is the product of the vector elements.
  • print(prod(x)): Calculates and prints the product of the elements in vector x, which is 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 divide two vectors of integers type and length 3.
Next: Write a R program to find Sum, Mean and Product of a Vector, ignore element like NA or NaN.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-6.php