The rowSums() function in R returns the sum of each row of a matrix, array, or data frame. You can also use this function to calculate the sum of the columns by setting the MARGIN argument to 1. In this guide, we will discuss the rowSums() function in R with examples.
Syntax
(x, na.rm = FALSE)
Arguments
- x = A matrix, array or data frame.
- na.rm = TRUE to ignore NA values. The default value is FALSE.
Example 1: Using rowSums() Function with a Matrix
# creating a matrix m <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3) # printing the matrix m # summing rows of the matrix rowSums(m)
Output
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [1] 9 12
Example 2: Using rowSums() Function with a Matrix
# creating an array a <- array(c(1,2,3,4,5,6), dim = c(2,3)) # printing the array a # summing rows of the array rowSums(a)
Output
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [1] 9 12
Example 3: Using rowSums() Function with a Data Fram
#creating a data frame df <- data.frame(x = c(1,2,3), y = c(4,5,6), z = c(7,8,9)) # printing a data frame df # summing rows of the data frame rowSums(df)
Output
x y z 1 1 4 7 2 2 5 8 3 3 6 9 [1] 12 15 18
Example 4: Using rowSums() Function to handle NA Values
By default, the rowSums() function returns an NA value for any row that contains an NA value. However, you can use the na.rm argument to remove NA values before calculating the row sums. Consider the following example, where our matrix has an NA value:
#creating a matrix m <- matrix(c(1,2,3,4,NA,6), nrow = 2, ncol = 3) #printing the matrix m #summing rows with NA values rowSums(m) #summing rows by removing NA values rowSums(m, na.rm = TRUE)
Output
[,1] [,2] [,3] [1,] 1 3 NA [2,] 2 4 6 [1] NA 12 [1] 4 12
As you can see, the function returned NA when na.rm was set to FALSE (by default).