Pablita
Pablita

Reputation: 89

Add multiple columns in R representing different categories

I have the following data frame in R:

Kingdom  D1 D2 D4 H1 H5
Animals  2   4  4  6  7
Bacteria 4   3  1  2  4
Viruses  1   4  4  5  6

I am trying to obtain the sum of each column while maintaining the first column even though every row has a unique name. I want to rename the row on the first column to "totals" after every other column has been added up.

The desired output should look like this:

Kingdom  D1 D2 D4 H1 H5
Totals    7 11  9 13 17

I have tried the following command in R: sum_df<-colSums(df[sapply(df, is.numeric)], na.rm = TRUE)

However this command doesn't maintain the first column and I am not sure how to do that. Also it gives me all the totals in a column format, not keeping the row format. D1 7 D2 11 D4 9 H1 13 H5 17

I have tried the transpose t() function to convert these columns back to a row, but I still don't know how to keep that first column like the desired output I showed. Any help is greatly appreciated! Thanks in advance!

Upvotes: 0

Views: 147

Answers (1)

LetEpsilonBeLessThanZero
LetEpsilonBeLessThanZero

Reputation: 2403

I know you already got an answer, but here's another solution using the dplyr package. I like it this solution, because the code is nice and readable.

library(dplyr)

df = data.frame(Kingdom = c("Animals", "Bacteria", "Viruses"),
                  D1 = c(2,4,1),
                  D2 = c(4,3,4),
                  D4 = c(6,2,5),
                  H1 = c(6,2,5),
                  H5 = c(7,4,6))

total_df = df %>%
  summarise(Kingdom = "Totals",
            sumD1 = sum(D1),
            sumD2 = sum(D2),
            sumD4 = sum(D4),
            sumH1 = sum(H1),
            sumH5 = sum(H5))

Upvotes: 2

Related Questions