How to Use the rowsums() Function in R (4 Examples)

The rowSums() function in R is “used to calculate the sum of values in each row of a matrix or data frame.

Syntax

rowSums(x, na.rm=FALSE) 

Parameters

  1. x: It is the name of the matrix or data frame.
  2. na.rm: It is a logical argument. If TRUE, NA values are ignored.

Example 1: Use the rowSums() with Data Frame

The rowSums() to find the sum of the values in each data frame row.

library(dplyr)

# Create a data frame.
df <- data.frame(
  x = c(11, 21, 31, 41, 51),
  y = c(1, 2, 3, 4, 5)
)

# Calculate the row sums.
rowSums(df)

Output

[1] 12 23 34 45 56

Example 2: Use rowSums() with NA Values in Data Frame

You can find the sum of the values in each data frame row when there are NA values in some rows using the na.rm = TRUE argument.

library(dplyr)

# Create a data frame.
df <- data.frame(
  x = c(11, 21, 31, NA, 51),
  y = c(1, 2, NA, 4, 5)
)

# Calculate the row sums.
rowSums(df, na.rm = TRUE)

Output

[1] 12 23 31 4 56

Example 3: Use the rowSums() with specific rows

You can use the rowSums() to find the sum of the values in specific rows of a data frame.

library(dplyr)

# Create a data frame.
df <- data.frame(
  x = c(11, 21, 31, NA, 51),
  y = c(1, 2, NA, 4, 5),
  z = c(19, 46, NA, 30, 53),
  w = c(11, 11, 20, 39, 49)
)

rowSums(df[c(1, 2, 3), ], na.rm = TRUE)

Output

  1   2  3
 42  80  51

Example 4: Use the rowSums() with matrix

To calculate the sum of row values of the matrix in R, use the “rowSums()” function.

rv <- rep(1:4)

mtrx <- matrix(rv, 2, 2)
mtrx
cat("The sum of rows is: ", "\n")
rowSums(mtrx)

Output

     [,1] [,2]
[1,]   1    3
[2,]   2    4

The sum of rows is:

[1] 4  6

That’s it.

Leave a Comment