通过另一个条件过滤一个数据框 [英] filter one dataframe via conditions in another
问题描述
我想通过任意数量的条件(表示为另一个数据框 z
中的行)来递归地过滤数据 d
.
I want to recursively filter a dataframe, d
by an arbitrary number of conditions (represented as rows in another dataframe z
).
我从一个数据框开始 d
:
d <- data.frame(x = 1:10, y = letters[1:10])
第二个数据帧 z
具有列 x1
和 x2
的列,它们是过滤 d $ x <的上下限/code>.此数据框
z
可能会增长为任意数量的行长.
The second dataframe z
, has columns x1
and x2
, which are lower and upper limits to filter d$x
. This dataframe z
may grow to be an arbitrary number of rows long.
z <- data.frame(x1 = c(1,3,8), x2 = c(1,4,10))
我想返回 d
的所有行,其中 d $ x< = z $ x1 [i]
和 d $ x> = z$ x2 [i]
表示所有 i
,其中 i = nrow(z)
.
I want to return all rows of d
for which d$x <= z$x1[i]
and d$x >= z$x2[i]
for all i
, where i = nrow(z)
.
因此,对于此玩具示例,请排除1:1、3:4、8:10(包括1和2)中的所有内容.
So for this toy example, exclude everything from 1:1, 3:4, 8:10, inclusive.
x y
2 2 b
5 5 e
6 6 f
7 7 g
推荐答案
我们可以在 x1
和 x2
值之间创建一个序列,并使用 anti_join
从 d
中选择 z
中不存在的行.
We can create a sequence between x1
and x2
values and use anti_join
to select rows from d
that are not present in z
.
library(tidyverse)
remove <- z %>%
mutate(x = map2(x1, x2, seq)) %>%
unnest(x) %>%
select(x)
anti_join(d, remove)
# x y
#1 2 b
#2 5 e
#3 6 f
#4 7 g
这篇关于通过另一个条件过滤一个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!