简体   繁体   English

在R中添加代表不​​同类别的多个列

[英]Add multiple columns in R representing different categories

I have the following data frame in R: 我在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) 我在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 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. 我已经尝试过转置t()函数将这些列转换回行,但是我仍然不知道如何像我展示的那样保持第一列。 Any help is greatly appreciated! 任何帮助是极大的赞赏! Thanks in advance! 提前致谢!

I know you already got an answer, but here's another solution using the dplyr package. 我知道您已经有了答案,但这是使用dplyr软件包的另一种解决方案。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM