Find Sum, Mean and Product of a Vector in R

• Difficulty Level : Basic
• Last Updated : 26 Mar, 2021

sum(), mean(), and prod() methods are available in R which are used to compute the specified operation over the arguments specified in the method. In case, a single vector is specified, then the operation is performed over individual elements, which is equivalent to the application of for loop.

Function Used:

• mean() function is used to calculate mean

Syntax: mean(x, na.rm)

Parameters:

• x: Numeric Vector
• na.rm: Boolean value to ignore NA value
• sum() is used to calculate sum

Syntax: sum(x)

Parameters:

• x: Numeric Vector
• prod() is used to calculate product

Syntax: prod(x)

Parameters:

• x: Numeric Vector

Example 1:

R

 vec = c(1, 2, 3 , 4)print("Sum of the vector:")  # inbuilt sum method print(sum(vec))  # using inbuilt mean methodprint("Mean of the vector:")print(mean(vec))    # using inbuilt product methodprint("Product of the vector:")print(prod(vec))

Output

 “Sum of the vector:”

 10

 “Mean of the vector:”

 2.5

 “Product of the vector:”

 24

Example 2:

R

 vec = c(1.1, 2, 3.0 )print("Sum of the vector:")  # inbuilt sum method print(sum(vec))  # using inbuilt mean methodprint("Mean of the vector:")print(mean(vec))    # using inbuilt product methodprint("Product of the vector:")print(prod(vec))

Output

 “Sum of the vector:”

 6.1

 “Mean of the vector:”

 2.033333

 “Product of the vector:”

 6.6

Example 3 : Vector with NaN values

R

 # declaring a vectorvec = c(1.1,NA, 2, 3.0,NA )print("Sum of the vector:")  # inbuilt sum method print(sum(vec))  # using inbuilt mean methodprint("Mean of the vector with NaN values:")  # not ignoring NaN valuesprint(mean(vec))    # ignoring missing valuesprint("Mean of the vector without NaN values:")print(mean(vec,na.rm = TRUE))    # using inbuilt product methodprint("Product of the vector:")print(prod(vec))

Output

 “Sum of the vector:”

 NA

 “Mean of the vector with NaN values:”

 NA

 “Mean of the vector without NaN values:”

 2.033333

 “Product of the vector:”

 NA

My Personal Notes arrow_drop_up