Reputation: 183
I have two data.frames
and I desire to know if the values in df_1
are included in the min and max range of df_2
.
Here my example:
df_1 = data.frame(x = c(0.5, 0.75, 0.15, 0.1))
df_2 = data.frame(min = c(0.2, 0.5, 0.1, 0.6), max = c(0.9, 0.6, 0.35, 1))
The desired output should be e.g. just a logical vector of TRUE or FALSE, and in this case the desired output is:
> out
[1] TRUE FALSE TRUE FALSE
It should be trivial but I couldn't find an answer so far.
Any suggestion will be grateful.
Upvotes: 0
Views: 43
Reputation: 4873
You can also do this:
df_1$x %in% c(df_2$min, df_2$max)
[1] TRUE FALSE FALSE TRUE
Which also allows you to use it for indexing, for example:
df_1[df_1$x %in% c(df_2$min, df_2$max),]
[1] 0.5 0.1
Upvotes: 2
Reputation: 161110
You need nothing but base R for this:
df_2$min <= df_1$x & df_1$x <= df_2$max
No need for dplyr
or anything else in the tidyverse
. If you really wanted it, though, you could always do:
dplyr::between(df_1$x, df_2$min, df_2$max)
for perhaps slightly better readability (albeit a little worse code-golf).
Upvotes: 3
Reputation: 2717
df_1%>%
dplyr::bind_cols(df_2)%>%
mutate(res=if_else(x<min | x>max,F,T))%>%
.[,"res"]
Upvotes: 1