How to Add a Total Row to a Data Frame in R


You can use the following methods to add a ‘total’ row to the bottom of a data frame in R:

Method 1: Use Base R

rbind(df, data.frame(team='Total', t(colSums(df[, -1]))))

Method 2: Use dplyr

library(dplyr)

df %>%
  bind_rows(summarise(., across(where(is.numeric), sum),
                         across(where(is.character), ~'Total')))

The following example shows how to use each method in practice with the following data frame:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E', 'F'),
                 assists=c(5, 7, 7, 9, 12, 9),
                 rebounds=c(11, 8, 10, 6, 6, 5),
                 blocks=c(6, 6, 3, 2, 7, 9))

#view data frame
df

  team assists rebounds blocks
1    A       5       11      6
2    B       7        8      6
3    C       7       10      3
4    D       9        6      2
5    E      12        6      7
6    F       9        5      9

Example 1: Add Total Row Using Base R

We can use the rbind and colSums functions from base R to add a total row to the bottom of the data frame:

#add total row to data frame
df_new <- rbind(df, data.frame(team='Total', t(colSums(df[, -1]))))

#view new data frame
df_new

   team assists rebounds blocks
1     A       5       11      6
2     B       7        8      6
3     C       7       10      3
4     D       9        6      2
5     E      12        6      7
6     F       9        5      9
7 Total      49       46     33

Notice that a row has been added to the bottom of the data frame that shows the sum of the values in each column.

Example 2: Add Total Row Using dplyr

The following code shows how to use functions from the dplyr package in R to add a total row to the bottom of the data frame:

library(dplyr)

#add total row to data frame
df_new <- df %>%
            bind_rows(summarise(., across(where(is.numeric), sum),
                                   across(where(is.character), ~'Total')))

#view new data frame
df_new

   team assists rebounds blocks
1     A       5       11      6
2     B       7        8      6
3     C       7       10      3
4     D       9        6      2
5     E      12        6      7
6     F       9        5      9
7 Total      49       46     33

Notice that a row has been added to the bottom of the data frame that shows the sum of the values in each column.

Also notice that this method produces the same results as the base R method.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use rbind in R
How to Remove Rows in R
How to Calculate Difference Between Rows in R

Leave a Reply

Your email address will not be published. Required fields are marked *