【问题标题】:calculate the sum per 2 columns计算每 2 列的总和
【发布时间】:2014-06-23 04:24:05
【问题描述】:

我有以下数据框:

all <- structure(list(counts = c(0L, 0L, 3L, 0L, 2L, 0L), counts = c(0L, 
2L, 1L, 0L, 5L, 1L), counts = c(1L, 9L, 17L, 0L, 7L, 2L), counts = c(2L, 
1L, 13L, 0L, 7L, 5L), counts = c(1L, 1L, 3L, 0L, 2L, 10L), counts = c(0L, 
2L, 2L, 0L, 8L, 9L), counts = c(0L, 4L, 4L, 0L, 4L, 0L), counts = c(0L, 
2L, 3L, 0L, 7L, 1L), counts = c(0L, 2L, 0L, 0L, 3L, 8L), counts = c(1L, 
3L, 3L, 0L, 4L, 13L), counts = c(0L, 6L, 12L, 0L, 3L, 2L), counts = c(0L, 
7L, 6L, 0L, 4L, 2L), counts = c(1L, 0L, 1L, 0L, 2L, 5L), counts = c(1L, 
1L, 2L, 0L, 3L, 6L), counts = c(0L, 2L, 1L, 1L, 2L, 0L), counts = c(0L, 
4L, 1L, 0L, 4L, 0L), counts = c(0L, 2L, 1L, 0L, 3L, 3L), counts = c(0L, 
1L, 1L, 0L, 2L, 1L), counts = c(0L, 3L, 1L, 0L, 5L, 0L), counts = c(0L, 
4L, 5L, 0L, 1L, 0L), counts = c(0L, 2L, 5L, 0L, 8L, 23L), counts = c(0L, 
0L, 2L, 0L, 1L, 7L), counts = c(1L, 0L, 0L, 0L, 1L, 2L), counts = c(0L, 
0L, 0L, 0L, 1L, 0L)), .Names = c("counts", "counts", "counts", 
"counts", "counts", "counts", "counts", "counts", "counts", "counts", 
"counts", "counts", "counts", "counts", "counts", "counts", "counts", 
"counts", "counts", "counts", "counts", "counts", "counts", "counts"
), row.names = c("1/2-SBSRNA4", "A1BG", "A1BG-AS1", "A1CF", "A2LD1", 
"A2M"), class = "data.frame")

在这个数据框中,我需要以最简单的形式计算每 2 列的总和,这可以通过以下方式完成:all[1] + all[2]、all[3] + all[4] 等等,然后在最后我可以再次 cbind 新框架,但我现在可以通过聚合或应用之类的方法来完成。只有我还没有成功。我现在最好的尝试是:allfinal &lt;-aggregate( all ,FUN = sum,by=[1:2] ) 我知道这不是它应该如何工作但无法弄清楚如何正确使用聚合或(S)应用来做到这一点。任何提示表示赞赏!

作为输出,我希望有一个数据框,每 1 列包含 2 列的总和。 data.frame 现在有 24 列,所以最后我需要 12 列。

【问题讨论】:

  • 我可能只会做all[c(T,F)]+all[c(F,T)]
  • @jdharrison 这工作得更好我必须说,因为这里我的数据框仍然是一个数据框,下面的答案是创建一个矩阵

标签: r sum aggregate


【解决方案1】:

你可以试试这个:

 t(rowsum(t(all), gl(ncol(all)/2, 2)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多