r - 根据 R 中的多个条件计算字符出现次数
问题描述
我正在尝试根据多个条件计算数据框中多个不同字符串的出现次数。我有以下包含以下信息的数据框(mut.total):
TYPE Sample Genotype Mutagen Dose
1 DUP CD0001c N2 MA 20
2 DEL CD0001d N2 MA 20
3 DUP CD0030a N2 MA 20
4 DEL CD0035a N2 Mechlorethamine 20
5 INV CD0035a N2 Mechlorethamine 20
6 INV CD0035a N2 Mechlorethamine 20
7 DUP CD0035a N2 Mechlorethamine 20
8 DEL CD0035a N2 Mechlorethamine 20
9 DEL CD0035c N2 Mechlorethamine 20
10 DUP CD0035d N2 Mechlorethamine 20
我想生成一个数据框,按诱变剂和类型显示突变总数和突变来自的样本数量(请记住,一个样本可能会产生相同类型的多个突变)。我的预期输出示例:
Mutagen Type N.Mut N.Sample
1 MA DEL 1 1
2 Mechlorethamine DEL 3 2
3 MA DUP 2 2
4 Mechlorethamine DUP 2 2
5 Mechlorethamine INV 2 1
使用聚合我能够按诱变剂和类型生成突变数量,但我无法弄清楚如何添加突变来自的样本数量。
aggregate(x=mut.total$TYPE, by=list(Mutagen = mut.total$Mutagen, Type = mut.total$TYPE),
FUN = length)
Mutagen Type N.Mut
1 MA DEL 1
2 Mechlorethamine DEL 3
3 MA DUP 2
4 Mechlorethamine DUP 2
5 Mechlorethamine INV 2
解决方案
这是一个dplyr
版本:
library(dplyr)
mut.total %>%
group_by(Mutagen, TYPE) %>%
summarise(N.Mut = n(), N.Sample = n_distinct(Sample))
输出
Mutagen TYPE N.Mut N.Sample
<chr> <chr> <int> <int>
1 MA DEL 1 1
2 MA DUP 2 2
3 Mechlorethamine DEL 3 2
4 Mechlorethamine DUP 2 2
5 Mechlorethamine INV 2 1
推荐阅读
- postgresql - 为地理类型添加唯一约束
- html - 有什么更好的方法来创建这种可以在多个设备上保持响应以及使用 twitter 引导程序的精确布局?
- php - Laravel nova 使资源只显示用户的数据
- python - 代码在本地运行良好,但部署到 heroku 时得到“错误:(-215:断言失败)!image.empty()”
- java - 在自定义存储库中使用 SpringBoot 和 JPA Criteria Query 查询时间戳
- javascript - 通过ajax发送2个数组
- python - 如何减少处理大数据框的时间
- javascript - 使用javascript和php的src切换
- shell - 在 shell 脚本中使用 sudo
- freemarker - Freemarker 和换行符空白