fastread homefastrread library fastread menu

R Programming : Find Sum, Mean and Product of Vector Elements

Tutorial by:Maria Ghoste      Date: 2016-06-10 03:21:27

❰ Previous Next ❱

We can sum the elements of a vector using the sum() function. Similarly, mean() and prod() functions can be used to find the mean and product of the terms.

Source Code

> sum(2,7,5)
[1] 14

> x
[1]  2 NA  3  1  4

> sum(x)    # if any element is NA or NaN, result is NA or NaN
[1] NA

> sum(x, na.rm=TRUE)    # this way we can ignore NA and NaN values
[1] 10

> mean(x, na.rm=TRUE)
[1] 2.5

> prod(x, na.rm=TRUE)
[1] 24

Whenever a vector contains NA (Not Available) or NaN (Not a Number), functions such as sum(), mean(), prod() etc. produce NA or NaN respectively. In order to ignore such values, we pass in the argument na.rm=TRUE.

❰ Previous Next ❱


R Programming

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website