R - 子集数据框 - 检查值是否在范围内 [英] R - subset data frame - check if value lies in range
本文介绍了R - 子集数据框 - 检查值是否在范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下两个数据框
d1 <- data.frame(chr = c("chr1","chr2","chr2"), pos = c(11, 15,21), type = c("type1","type2","type1"))
> d1
chr pos type
1 chr1 11 type1
2 chr2 15 type2
3 chr2 21 type1
d2 <- data.frame(chr = c("chr1","chr2","chr4"), start = c(10, 15,30), stop = c(13,20,40))
> d2
chr start stop
1 chr1 10 13
2 chr2 15 20
3 chr4 30 40
我想在两个条件下对 d1 进行子集化:
I want to subset d1 on two conditions:
- 保留所有type"==type1"的行(我知道怎么做)
- 保留 'chr' 匹配 d2 中任何行的所有行,并且 'pos' 位于 d2 中该行的 'start' 和 'stop' 值之间
在这种情况下,生成的 d3 将只包含 d1 的第 1 行:
The resulting d3 would in this case then only contain line 1 of d1:
> d3
chr pos type
1 chr1 11 type1
我会这样开始:
d3 <- subset(d1, d1$type == "type1" & ...)
推荐答案
我们可以把所有的条件加在一起成为一个逻辑条件子集
We can add all the conditions together into one logical condition to subset
d1[d1$type=="type1" & d1$chr %in% d2$chr & d1$pos >= d2$start & d1$pos <= d2$stop, ]
# chr pos type
#1 chr1 11 type1
这篇关于R - 子集数据框 - 检查值是否在范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文