# Get Sum of Data Frame Column Values in R (2 Examples)

In this article youâ€™ll learn how to **compute the sum of one or all columns of a data frame** in the R programming language.

Table of contents:

Letâ€™s do this:

## Introducing Example Data

As a first step, weâ€™ll have to create some data that we can use in the examples later on:

data <- data.frame(x1 = 1:5, # Create example data x2 = 2:6, x3 = 3) data # Return example data # x1 x2 x3 # 1 1 2 3 # 2 2 3 3 # 3 3 4 3 # 4 4 5 3 # 5 5 6 3

The previous output of the RStudio console shows that our example data has five rows and three columns. Each of the three variables is numeric.

## Example 1: Compute Sum of One Column Using sum() Function

In Example 1, Iâ€™ll explain how to return the sum of only one variable of our data frame (i.e. x1). For this, we can use the sum function as shown below:

sum(data$x1) # Applying sum function # 15

The sum of all values contained in the column x1 is 15.

## Example 2: Compute Sum of All Columns Using colSums() Function

We can also compute the sum of all numeric columns of our data frame. The following R code explains how to do this using the colSums function in R.

colSums(data) # Applying colSums function # x1 x2 x3 # 15 20 15

The output of the colsums function illustrates the column sums of all variables in our data frame.

## Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video, Iâ€™m showing the R programming code of this article:

**Please accept YouTube cookies to play this video.** By accepting you will be accessing content from YouTube, a service provided by an external third party.

If you accept this notice, your choice will be saved and the page will refresh.

In addition, you could read the related articles on my website. You can find a selection of articles about descriptive statistics below.

- sum Function in R
- colSums, rowSums, colMeans & rowMeans in R
- cumsum Function in R
- R Programming Language

In this R programming post you learned how to **calculate sums of variables**. In case you have any further questions, please let me know in the comments section below.

### Statistics Globe Newsletter