R summaryBy或其他汇总方法

时间:2014-11-13 03:13:04

标签: r dplyr

我正在尝试创建一个摘要表并进行心理挂断。基本上,我认为我想要的是一个summaryBy语句获取所有列的子集的colSums,除了要汇总的因子。

我的数据框如下所示:

                   Cluster GO:0003677 GO:0003700 GO:0046872 GO:0008270 GO:0043565 GO:0005524
comp103680_c0      10          0          0          0          0          0          1
comp103947_c0       3          0          0          0          0          0          0
comp104660_c0       1          1          1          0          0          0          0
comp105255_c0       10          0          0          0          0          0          0

我想做的是在Cluster使用Cluster作为分组因子后获取所有列的colSums。

我尝试了很多东西。最后一个是ply ddply

> groupColumns = "Cluster"
> dataColumns = colnames(GO_matrix_MF[,2:ncol(GO_matrix_MF)])
> res = ddply(GO_matrix_MF, groupColumns, function(x) colSums(GO_matrix_MF[dataColumns]))
> head(res)
  Cluster GO:0003677 GO:0003700 GO:0046872 GO:0008270 GO:0043565 GO:0005524 GO:0004674 GO:0045735
1       1        121        138        196         94         43        213         97         20
2       2        121        138        196         94         43        213         97         20

我不确定返回值代表什么,但它们不代表colSums

2 个答案:

答案 0 :(得分:1)

尝试:

> aggregate(.~Cluster, data=ddf, sum)
  Cluster GO.0003677 GO.0003700 GO.0046872 GO.0008270 GO.0043565 GO.0005524
1       1          1          1          0          0          0          0
2       3          0          0          0          0          0          0
3      10          0          0          0          0          0          1

答案 1 :(得分:1)

我认为你正在寻找这样的东西。我稍微修改了你的数据。还有其他选择。

# Modified data
foo <- structure(list(Cluster = c(10L, 3L, 1L, 10L), GO.0003677 = c(11L, 
0L, 1L, 5L), GO.0003700 = c(0L, 0L, 1L, 0L), GO.0046872 = c(0L, 
9L, 0L, 0L), GO.0008270 = c(0L, 0L, 0L, 0L), GO.0043565 = c(0L, 
0L, 0L, 0L), GO.0005524 = c(1L, 0L, 0L, 0L)), .Names = c("Cluster", 
"GO.0003677", "GO.0003700", "GO.0046872", "GO.0008270", "GO.0043565", 
"GO.0005524"), class = "data.frame", row.names = c("comp103680_c0", 
"comp103947_c0", "comp104660_c0", "comp105255_c0"))

library(dplyr)
foo %>%
    group_by(Cluster) %>%
    summarise_each(funs(sum))

# Cluster GO.0003677 GO.0003700 GO.0046872 GO.0008270 GO.0043565 GO.0005524
#1       1          1          1          0          0          0          0
#2       3          0          0          9          0          0          0
#3      10         16          0          0          0          0          1