【问题标题】:I am trying to sum probes count within subgroup of a dataframe in R [duplicate]我正在尝试对 R 中数据帧的子组内的探测计数求和 [重复]
【发布时间】:2025-12-29 09:15:12
【问题描述】:

我是一名生物化学专业的学生,​​研究乳腺癌数据(拷贝数探针)。我有以下原发性乳腺肿瘤的数据框:

Patient   Chrom   Start    End       ProbeCount
1         1       51599    62640     8
1         1       88466    16022503  8676
1         2       2785     285255    186
1         2       290880   4178544   2903
...
2         1       51599    4098530   1282
2         1       4101675  46753618  25229
2         2       2785     36178040  25931
2         2       36185342 36192717  21
...

我想添加第五列,我可以在其中添加每个患者的每个 Chrom 的 ProbeCounts 总数:

Patient   Chrom   Start    End       ProbeCount   Total
1         1       51599    62640     8            8684
1         1       88466    16022503  8676         8684
1         2       2785     285255    186          3089
1         2       290880   4178544   2903         3089
...
2         1       51599    4098530   1282         26511
2         1       4101675  46753618  25229        26511
2         2       2785     36178040  25931        25952
2         2       36185342 36192717  21           25952
...

为此必须有一个简单的函数。总计的?如果有人可以给我一个提示,我将不胜感激。谢谢!

【问题讨论】:

  • 这个问题至少有 500 种不同的形式被问过,请尝试搜索dplyr,或data.tablegroup by。我从不久前挑选了一个相当可靠的答案,但还有很多类似的答案。

标签: r sum


【解决方案1】:

dplyr 包的一种方法如下。您的数据框称为mydf

library(dplyr)
group_by(mydf, Patient, Chrom) %>%
mutate(whatever = sum(ProbeCount))

#Source: local data frame [8 x 6]
#Groups: Patient, Chrom
#
#  Patient Chrom    Start      End ProbeCount whatever
#1       1     1    51599    62640          8     8684
#2       1     1    88466 16022503       8676     8684
#3       1     2     2785   285255        186     3089
#4       1     2   290880  4178544       2903     3089
#5       2     1    51599  4098530       1282    26511
#6       2     1  4101675 46753618      25229    26511
#7       2     2     2785 36178040      25931    25952
#8       2     2 36185342 36192717         21    25952

如果您的数据很大,您可能需要使用data.table

library(data.table)
setDT(mydf)[, whatever := sum(ProbeCount), by = list(Patient, Chrom)][]

#   Patient Chrom    Start      End ProbeCount whatever
#1:       1     1    51599    62640          8     8684
#2:       1     1    88466 16022503       8676     8684
#3:       1     2     2785   285255        186     3089
#4:       1     2   290880  4178544       2903     3089
#5:       2     1    51599  4098530       1282    26511
#6:       2     1  4101675 46753618      25229    26511
#7:       2     2     2785 36178040      25931    25952
#8:       2     2 36185342 36192717         21    25952

【讨论】: