# Sums of Rows & Columns in Data Frame or Matrix in R (2 Examples)

In this tutorial, Iâ€™ll illustrate how to calculate row and column sums in the R programming language.

With that, letâ€™s dive right into the exemplifying R syntax.

## Construction of Example Data

First, weâ€™ll have to create some data that we can use in the examples below:

```data <- data.frame(x1 = 1:5,    # Creating example data
x2 = 9:5,
x3 = c(4, 1, 6, 9, 1))
data                            # Printing example data
#   x1 x2 x3
# 1  1  9  4
# 2  2  8  1
# 3  3  7  6
# 4  4  6  9
# 5  5  5  1```

The previous output of the RStudio console shows the structure of our example data â€“ It consists of five rows and three columns. All variables of our data frame have the numeric class.

## Example 1: Computing Sums of Data Frame Rows Using rowSums() Function

Example 1 illustrates how to sum up the rows of our data frame using the rowSums function in R.

```rowSums(data)                   # Applying rowSums function
# [1] 14 11 16 19 11```

The RStudio console output of the rowSums function is a numeric vector. Each element of this vector is the sum of one row, i.e. the sum of row 1 is 14, the sum of row 2 is 11, and so onâ€¦

## Example 2: Computing Sums of Data Frame Columns Using colSums() Function

In Example 2, Iâ€™ll illustrate how to get the sum of all variables of our data matrix using the colSums function.

```colSums(data)                   # Applying colSums function
# x1 x2 x3
# 15 35 21```

The output is a named vector that consists of one named element for each column of our data table. The sum of the variable x1 is 15, the sum of the variable x2 is 35, and the sum of the variable x3 is 21.

## Video, Further Resources & Summary

In case you need more explanations on the topics of this tutorial, you may have a look at the following video of my YouTube channel. In the video, I explain the R programming codes of this article in RStudio:

Furthermore, I can recommend reading the other articles which I have published on this website. I have published numerous posts about descriptive statistics already.

Summary: In this post you learned how to sum up the rows and columns of a data set in R programming. Let me know in the comments, if you have any further questions.

Subscribe to the Statistics Globe Newsletter