R 按级别组合计算数据帧过滤的行数
我有这个数据帧(这是我的芯片序列数据的8个不同床文件之间的multibedintersect的输出): 列“list”是一个字符串,表示样本列表中存在的特定峰值 例如,峰值“2”出现在样本编号6和7中。 我想计算在数据集中发现2个样本的每个组合的次数,创建一个汇总信息的表 所以基本上多层相交会返回太多的重叠。我只是对当时样本之间的重叠感兴趣 例如,样本6和7出现在峰2,21,28中,样本4和6出现在峰21和28中 通过软件包,我当时能够解决1个样本的问题,但我不能为每个组合“使其循环”R 按级别组合计算数据帧过滤的行数,r,subset,R,Subset,我有这个数据帧(这是我的芯片序列数据的8个不同床文件之间的multibedintersect的输出): 列“list”是一个字符串,表示样本列表中存在的特定峰值 例如,峰值“2”出现在样本编号6和7中。 我想计算在数据集中发现2个样本的每个组合的次数,创建一个汇总信息的表 所以基本上多层相交会返回太多的重叠。我只是对当时样本之间的重叠感兴趣 例如,样本6和7出现在峰2,21,28中,样本4和6出现在峰21和28中 通过软件包,我当时能够解决1个样本的问题,但我不能为每个组合“使其循环”
Table %>%
filter(str_detect(list, "6,7"))
通过这种方式,我可以找回任何具有这种组合的东西:
chrom start end num list
2 chr1 4491607 4493602 2 6,7
21 chr1 7139275 7139745 3 4,6,7
28 chr1 9745462 9745912 4 1,4,6,7
我认为这表现不佳,而且脚本非常密集,因为我需要手动筛选每个组合:
举几个例子:
- 7,8
- 6,8
- 5,8
- 4,8
- 3,8
- 2,8
- 1,8
- 6,7
- 继续
Counts <- NULL
Pippo <- Table %>%
filter(str_detect(list, "7,8"))
Counts <- cbind(nrow(Pippo))
Pippo <- Table %>%
filter(str_detect(list, "6,8"))
Counts <- cbind(Counts, nrow(Pippo))
Pippo <- Table %>%
filter(str_detect(list, "5,8"))
Counts <- cbind(Counts, nrow(Pippo))
Pippo <- Table %>%
filter(str_detect(list, "4,8"))
Counts <- cbind(Counts, nrow(Pippo))
Pippo <- Table %>%
filter(str_detect(list, "3,8"))
Counts <- cbind(Counts, nrow(Pippo))
Pippo <- Table %>%
filter(str_detect(list, "2,8"))
Counts <- cbind(Counts, nrow(Pippo))
Pippo <- Table %>%
filter(str_detect(list, "1,8"))
Counts <- cbind(Counts, nrow(Pippo))
Counts考虑使用两个sapply
调用的base R:一个使用combn
构建所有对字符串,另一个使用grepl
对数据帧进行子集设置以检索行计数:
pairs <- sapply(combn(1:8, 2, simplify=FALSE), function(i) paste(i, collapse=","))
Counts <- sapply(pairs, function(i) nrow(subset(Table, grepl(i, `list`))))
Counts
# 1,2 1,3 1,4 1,5 1,6 1,7 1,8 2,3 2,4 2,5 2,6 2,7 2,8 3,4 3,5 3,6 3,7 3,8 4,5 4,6
# 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2
# 4,7 4,8 5,6 5,7 5,8 6,7 6,8 7,8
# 0 0 0 0 0 3 0 2
是否只希望连续发生?例如,如果列表的值是4,6,7
,那么对于其中的3个,该值是否算作4,7
,或者仅算作4,6
和6,7
!所以对于4,7 6,7 4,6这正是我想要的。我对Sapply很不满意:(你有推荐的视频教程吗?再次非常感谢!
pairs <- sapply(combn(1:8, 2, simplify=FALSE), function(i) paste(i, collapse=","))
Counts <- sapply(pairs, function(i) nrow(subset(Table, grepl(i, `list`))))
Counts
# 1,2 1,3 1,4 1,5 1,6 1,7 1,8 2,3 2,4 2,5 2,6 2,7 2,8 3,4 3,5 3,6 3,7 3,8 4,5 4,6
# 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2
# 4,7 4,8 5,6 5,7 5,8 6,7 6,8 7,8
# 0 0 0 0 0 3 0 2
pairs <- combn(1:8, 2, simplify=FALSE) %>%
map(~(paste(., collapse=","))) %>%
unlist()
Counts <- pairs %>%
map(~(filter(Table, str_detect(list, .)) %>% nrow)) %>%
setNames(pairs) %>%
unlist()
Counts
# 1,2 1,3 1,4 1,5 1,6 1,7 1,8 2,3 2,4 2,5 2,6 2,7 2,8 3,4 3,5 3,6 3,7 3,8 4,5 4,6
# 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2
# 4,7 4,8 5,6 5,7 5,8 6,7 6,8 7,8
# 0 0 0 0 0 3 0 2