Skip to content

Instantly share code, notes, and snippets.

@daltonjorge
Created July 22, 2021 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daltonjorge/cf95c8e0b1fe9518776cc3332c423496 to your computer and use it in GitHub Desktop.
Save daltonjorge/cf95c8e0b1fe9518776cc3332c423496 to your computer and use it in GitHub Desktop.
Add a total row to a R data frame
% Solution 1
original_data_frame <- data.frame(
name = c('John','Paul','Mary'),
age = c(25, 30, 20),
salary = c(90000, 110000,85000)
)
new_df_with_totals <- data.frame(
name = 'Total',
colSums(t(original_data_frame[,-1]))
)
rbind(original_data_frame, new_df_with_totals)
% Solution 2
new_df <- original_data_frame
new_df[4,] = c("Total", colSums(new_df[,2:3]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment