假设我有df1:
Start_Date End_Date Value
2001-01-01 2001-12-31 1
2002-01-01 2002-12-31 2
2003-01-01 2003-12-31 3
2004-01-01 2004-12-31 4
2005-01-01 2005-12-31 5
&df2:
DateTime Gain People
2003-01-01 3 3
2003-05-09 5 4
2004-12-31 1 2
2005-01-31 -2 2
2005-08-13 9 7
2006-09-10 6 8
2007-10-03 7 5
我想通过检查df2中的哪个DateTime介于df1的Start_Date和End_Date之间,将值从df1导入df2。如果日期不属于df1的任何时段,则返回值0。预期结果的视图:
DateTime Gain People Value
2003-01-01 3 3 3
2003-05-09 5 4 3
2004-12-31 1 2 4
2005-01-31 -2 2 5
2005-08-13 9 7 5
2006-09-10 6 8 0
2007-10-03 7 5 0
请告知
潜在的挑战在于不平等条件。这些在sql中很简单,但在R中则不然,因为dplyr仅在相等时才加入。 Here是S.O上主要答案的链接。
我发现最好的方法是进行更一般的联接,然后过滤不等式。
df1 = df1 %>% mutate(join_id = 1)
df2 = df2 %>% mutate(join_id = 1)
output = left_join(df2, df1, by = 'join_id') %>%
filter(Start_Date <= DateTime,
DateTime <= End_Date) %>%
select(DateTime, Gain, People, Value) %>%
mutate(Value = ifelse(is.na(Value), 0, Value)
说明:
ifelse(is.na(...
用于替换缺少的值。在某些情况下,这种更为通用的联接会产生性能问题。但是由于R默认情况下使用惰性求值,因此如果在联接之后立即进行过滤,则R应该将两个语句作为同一联接的一部分运行,并避免任何性能问题。