0

I have the following two dataframes:

df1:
column_01 column_02
a         3
b         7

df2:
column_01 column_02 column_03 column_04
a         1         4         a-low
a         5         8         a-high
b         1         4         b-low
b         5         8         b-high

I have to merge df1 with column_04 of df2, where column_01 of df1 matches column_01 of df2 AND column_02 of df1 has to be between the values of df2 column_02 and column_03. The result would be:

df_result:
column_01 column_02 column_03
a         3         a-low
b         7         b-high

In sql it would be a join with a between clause. But how can I get this done in R?

Kasper
  • 3
  • 2

1 Answers1

0

You can do this in two steps. First join, then filter. I use the package dplyr for this.

df1 <- data.frame(c1 = c('a','b'),
                  c2 = c(3,7))

df2 <- data.frame(c1 = c('a','a','b','b'),
                  c2 = c(1,5,1,5),
                  c3 = c(4,8,4,8),
                  c4 = c('al','ah','bl','bh'))

library(dplyr)

df1 %>% left_join(df2, by='c1') %>%
  filter(c2.x > c2.y, c2.x < c3)
Wietze314
  • 5,942
  • 2
  • 21
  • 40