Sum Function in R – sum()

Sum function in R – sum(), is used to calculate the sum of vector elements.

Syntax for R sum function :

sum(x, na.rm = FALSE, …)
  • x – numeric vector
  • rm- whether NA should be removed, if not, NA will be returned

 

Example of sum function in R

# R sum function

sum(1:10)
sum(c(2,5,6,7,1,2))

output:

[1] 55

[1] 23

 

 

Example of sum function in R with NA:

sum() function doesn’t give desired output, If NAs are present in the vector. so it has to be handled by using na.rm=TRUE in sum() function

# sum() function in R for input vector which has NA.

x <-c(1.234,2.342,-4.562,5.671,12.345,-14.567,NA)
sum(x,na.rm=TRUE)

output:

[1] 2.463

 

Example of sum() function in R for a column in data frame:

Lets use mtcars data frame to demonstrate sum function – sum() in r

# sum() function in R for column in data frame

sum(mtcars$mpg)

output:

[1] 642.9

previous small sum function in r                                                                                                                next small sum function in r