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

In this tutorial, I’ll explain how to calculate row and column sums in R.

Creating Example Data

data(iris)                      # Load iris data
iris_num <- iris[ , 1:4]        # Extract numeric columns
head(iris_num)                  # Head of numeric iris
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1          5.1         3.5          1.4         0.2
# 2          4.9         3.0          1.4         0.2
# 3          4.7         3.2          1.3         0.2
# 4          4.6         3.1          1.5         0.2
# 5          5.0         3.6          1.4         0.2
# 6          5.4         3.9          1.7         0.4

Example 1: Applying colSums Function to Compute Column Sums

colSums(iris_num)               # Use colSums()
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
#        876.5        458.6        563.7        179.9

Example 2: Applying rowSums Function to Compute Row Sums

rowSums(iris_num)               # Use rowSums()
# [1] 10.2  9.5  9.4  9.4 10.2 11.4  9.7 10.1  8.9  9.6 10.8 10.0  9.3  8.5 ...

Further Resources & Related Tutorials

You may find some related R programming tutorials on topics such as variables and the dplyr package in the following list:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top