How to Use rowSums() Function in R


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

Additional Resources

How to Sum Specific Columns in R (With Examples)
How to Sum Specific Rows in R (With Examples)

Leave a Reply

Your email address will not be published.