R Tutorial R Charts & Graphs R Statistics R References

R - sum() Function



The R sum() function returns sum of all elements present in the argument. The syntax for using this function is given below:

Syntax

sum(x1, x2, ..., na.rm = FALSE)

Parameters

x1, x2, ... Required. Specify numeric or complex or logical vectors.
na.rm Optional. Specify TRUE to remove NA or NaN values before the computation. Default is FALSE.

Return Value

Returns sum of all elements present in the argument.

Example:

The example below shows the usage of sum() function.

v1 <- c(10, 15, 20, 25, 30, 35)
v2 <- c(1, 2, 3, 4, 5)
cat("sum of all elements of v1:", sum(v1), "\n")
cat("sum of all elements of v2:", sum(v2), "\n")
cat("sum of all elements of v1 and v2:", sum(v1, v2), "\n")

m <- matrix(c(10, 20, 30, 40, 50, 60), ncol=2)
cat("\nThe matrix contains:\n")
print(m)
cat("sum of all elements of matrix:", sum(m))
cat("\nsum along first column of the matrix:", sum(m[,1]))

The output of the above code will be:

sum of all elements of v1: 135 
sum of all elements of v2: 15 
sum of all elements of v1 and v2: 150 

The matrix contains:
     [,1] [,2]
[1,]   10   40
[2,]   20   50
[3,]   30   60
sum of all elements of matrix: 210
sum along first column of the matrix: 60

Using na.rm parameter

The na.rm parameter can be set TRUE to remove NA or NaN values before the computation.

Example:

Consider the example below to see the usage of na.rm parameter.

v1 <- c(10, 20, 30, NA)
v2 <- c(10, 20, 30, NaN)

cat("sum of all elements of v1:", sum(v1), "\n")
cat("sum after removing NA:", sum(v1, na.rm=TRUE), "\n")

cat("\nsum of all elements of v2:", sum(v2), "\n")
cat("sum after removing NaN:", sum(v2, na.rm=TRUE), "\n")

The output of the above code will be:

sum of all elements of v1: NA 
sum after removing NA: 60 

sum of all elements of v2: NaN 
sum after removing NaN: 60 

❮ R Statistical Functions

5