R How to Compute Sums of Rows & Columns Using dplyr Package (2 Examples)
In this tutorial you’ll learn how to use the dplyr package to compute row and column sums in R programming.
Setting up the Examples
data(iris) # Load iris data iris_num <- iris[ , 1:4] # Remove non-numeric columns head(iris_num) # Head of updated 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 |
data(iris) # Load iris data iris_num <- iris[ , 1:4] # Remove non-numeric columns head(iris_num) # Head of updated 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
install.packages("dplyr") # Install & load dplyr package library("dplyr") |
install.packages("dplyr") # Install & load dplyr package library("dplyr")
Example 1: Computing Sums of Columns with dplyr Package
iris_num %>% # Column sums replace(is.na(.), 0) %>% # Replace NA with 0 summarise_all(sum) # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 876.5 458.6 563.7 179.9 |
iris_num %>% # Column sums replace(is.na(.), 0) %>% # Replace NA with 0 summarise_all(sum) # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 876.5 458.6 563.7 179.9
Example 2: Computing Sums of Rows with dplyr Package
iris_num %>% # Row sums replace(is.na(.), 0) %>% # Replace NA with 0 mutate(sum = rowSums(.)) # Sepal.Length Sepal.Width Petal.Length Petal.Width sum # 1 5.1 3.5 1.4 0.2 10.2 # 2 4.9 3.0 1.4 0.2 9.5 # 3 4.7 3.2 1.3 0.2 9.4 # 4 4.6 3.1 1.5 0.2 9.4 # 5 5.0 3.6 1.4 0.2 10.2 # 6 5.4 3.9 1.7 0.4 11.4 |
iris_num %>% # Row sums replace(is.na(.), 0) %>% # Replace NA with 0 mutate(sum = rowSums(.)) # Sepal.Length Sepal.Width Petal.Length Petal.Width sum # 1 5.1 3.5 1.4 0.2 10.2 # 2 4.9 3.0 1.4 0.2 9.5 # 3 4.7 3.2 1.3 0.2 9.4 # 4 4.6 3.1 1.5 0.2 9.4 # 5 5.0 3.6 1.4 0.2 10.2 # 6 5.4 3.9 1.7 0.4 11.4