What is the use of rowSums() Function in R?

The rowSums() Function in R is used to calculate the sum of the values of each row of a matrix or a data frame. It can also take an argument to specify which type of values should be included in the sum. This function is particularly useful for quickly obtaining the total of all values in a dataset or a matrix.


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

This function uses the following basic syntax:

rowSums(x, na.rm=FALSE)

where:

  • x: Name of the matrix or data frame.
  • na.rm: Whether to ignore NA values. Default is FALSE.

The following examples show how to use this function in practice.

Example 1: Use rowSums() with Data Frame

The following code shows how to use rowSums() to find the sum of the values in each row of a data frame:

#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 2, 5, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, 14, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    3    1
2    3    2    3    1
3    3    5    6    2
4    4    3    6   14
5    5    2    8    9

#find sum of each row
rowSums(df)

[1] 12  9 16 27 24

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

The following code shows how to use rowSums() to find the sum of the values in each row of a data frame when there are NA values in some rows:

#create data frame with some NA values
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, NA, NA, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, NA, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    3    1
2    3   NA    3    1
3    3   NA    6    2
4    4    3    6   NA
5    5    2    8    9

#find sum of each row
rowSums(df, na.rm=TRUE)

[1] 12  7 11 13 24

Example 3: Use rowSums() with Specific Rows

The following code shows how to use rowSums() to find the sum of the values in specific rows of a data frame:

#create data frame with some NA values
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, NA, NA, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, NA, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    3    1
2    3   NA    3    1
3    3   NA    6    2
4    4    3    6   NA
5    5    2    8    9

#find sum of rows 1, 3, and 5
rowSums(df[c(1, 3, 5), ], na.rm=TRUE)

 1  3  5 
12 11 24

x