r - 使用 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
.
.
.
解决方案
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)][]
推荐阅读
- javascript - WebStorm 如何知道要运行哪个测试?
- cypress - 赛普拉斯无法识别元素中实际存在的类
- c++ - 如何用 GetWindowsDirectoryA 返回结果具体化字符串?
- hash - 我们可以在智能合约中看到实际部署的输出吗?
- c++ - 在 VSCode 中配置 c++ 调试器
- pandas - 没有填充的熊猫 to_string?
- javascript - Vue app中axios调用后如何使用条件验证
- php - laravel 表达式无法转换为数字报错如何解决?
- c# - 使用子查询值过滤父结果,但仍返回与父项相关的所有子项
- solr - Apache Solr - 在不重新启动 solr 服务的情况下更新默认 log4j2.xml 文件