Skip to Content

R – Sum of values in a Vector

A vector is a one-dimensional data structure used to store data of the same type in R. Numeric vectors are commonly used to store a sequence of numbers. In this tutorial, we will look at how to get the sum of values in an R vector with the help of some examples.

How to get the sum of values in a vector in R?

You can use the R sum() function to get the sum of values in a vector. Pass the vector as an argument to the function. The following is the syntax –

# sum of values in a vector
sum(vec, na.rm=FALSE)

It also takes an additional (optional) argument, na.rm to indicate whether to remove missing values when computing the sum. It is FALSE by default.

The function returns the sum of values in the passed vector.

Examples

Let’s look at some examples of using the above method to get the sum of values in a vector.

Sum of values in a numeric vector

Let’s create a vector of numbers (and without any NA values) and apply the sum() function.

# create a vector
vec <- c(1, 2, 3)
# sum of values in vector
sum(vec)

Output:

6

We get the sum as 6, which is the correct sum of the values in the above vector, 1+2+3=6.

What would happen if there are some NA present values in the vector? Let’s find out. First, we will create a vector with some NA values and then apply the sum() function without any additional arguments.

# create a vector with NA values
vec <- c(1, 2, NA, 3, NA)
# sum of values in vector
sum(vec)

Output:

<NA>

You can see that we get NA as the output. This is because summing anything with NA results in NA in R.

Sum of values in a vector with NA values

You can pass TRUE to the na.rm parameter of the sum() function to exclude missing values when computing the sum in a vector.

# create a vector with NA values
vec <- c(1, 2, NA, 3, NA)
# sum of values in vector
sum(vec, na.rm=TRUE)

Output:

6

Now we get the sum of values in the above vector as 6.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.