首页 > 解决方案 > 使用 dplyr group_by 来查找每个组的分数 >= 2?

问题描述

我有一个在 R 中调用的数据框splicing,如下所示(简化):

Site    PhyloP_n
50      -1.546
50      -1.546
50      -1.546
49      2.125
49      2.125
48      -0.282
48      -0.282
47      0.596
47      0.596
46      3.561
46      3.561

每个在完整数据框中Site都有多个PhyloP_n分数。我想要做的是在每个站点获得 PhyloP_n 分数 >= 2 的分数。目前,这是我设置它的方式,但它不起作用:

splicing_high_phylop <- splicing %>%
  group_by(Site) %>%
  filter(PhyloP_n >= 2 )
  dplyr::summarize(Fraction = (sum(PhyloP_n >= 2, na.rm = TRUE) / tally()))

预期输出:

Site      Fraction with PhyloP_n >= 2
50        0.3
49        0.1
48        0.04
47        0.21
.
.
.

标签: rdplyr

解决方案


We can use data.table methods. Convert the 'data.frame' to 'data.table' (setDT(df)), grouped by 'Site', get the sum of logical vector (PhyloP_n >=2), and then update the 'Frac' by dividing with the sum of 'Frac'

library(data.table)
setDT(df)[, .(Frac = sum(PhyloP_n >=2, na.rm = TRUE)),
     by = Site][, Frac := Frac/sum(Frac)][]

推荐阅读