R – Sum of Vector Elements

In this tutorial, we will learn how to find the sum of vector elements in R programming Language.

To find the sum of vector elements in R, call sum() function and pass the vector as argument. sum() returns a new vector with the elements of first vector appended with that of second vector.

Syntax

The syntax to find the sum of elements in vector x is

</>
Copy
sum(x)

We can pass multiple vectors to sum(). The syntax to find the sum of vectors: x, y and z is

</>
Copy
sum(x, y, z)

To ignore NA or NaN values in vector for summing, pass TRUE for na.rm optional parameter.

</>
Copy
sum(x, na.rm=TRUE)

Examples

Sum of Elements in Vector

In this example, we take a vector x and find the sum of elements in it using sum().

Example.R

</>
Copy
x <- c(2, 4, 6)
result <- sum(x)
print(result)

Output

[1] 12

Sum of Elements in Multiple Vector

In this example, we take two vectors x and y, and find the sum of elements in both of these vectors.

Example.R

</>
Copy
x <- c(2, 4, 6)
y <- c(-8, 0, 2)
result <- sum(x, y)
print(result)

Output

[1] 6

Sum of Elements in Vector containing NA Values and Not Ignoring

In this example, we take a vector x, the contains NA values, and find the sum of elements in it using sum() not ignoring these NA values.

Example.R

</>
Copy
x <- c(2, 4, 6, NA)
result <- sum(x)
print(result)

Output

[1] NA

Sum of Elements in Vector containing NA Values and Ignoring

In this example, we take a vector x, the contains NA values, and find the sum of elements in it using sum() ignoring these NA values.

Example.R

</>
Copy
x <- c(2, 4, 6, NA)
result <- sum(x, na.rm = TRUE)
print(result)

Output

[1] 12

Conclusion

In this R Tutorial, we learned how to find the sum of vector elements in R using sum(), with the help of example programs.