dplyr中使用子集的条件左联接

问题描述 投票:0回答:1

我正在尝试使用dplyr在两个数据框之间执行条件左连接。我的第一个数据框df1:

ID  Start Date End Date
1   1-1-2000   4-1-2020

我的第二个数据帧,df2:

ID START_DT END_DT   Name
1  2-3-2002 3-1-2020 John Smith
1  4-2-2004 4-1-2021 Karen Anderson

我正在尝试加入开始日期> START_DT AND结束日期<= END_DT的ID

ID START_DT END_DT   Name        Start Date  End Date
1  2-3-2002 3-1-2020 John Smith  1-1-2000    4-1-2020

我已经尝试过,这给了我一个错误

new_df <- left_join(df2, df1, by = "ID") %>%
  subset(subset(new_df, `Start Date` > START_DT & `End Date` <= END_DT))

我也尝试过先进行连接然后再进行子集,这给了我

Warning messages:
1: In eval(e, x, parent.frame()) :
  Incompatible methods (">.POSIXt", "Ops.factor") for ">"
2: In eval(e, x, parent.frame()) :
  Incompatible methods ("<=.POSIXt", "Ops.factor") for "<="
r dplyr left-join conditional-operator
1个回答
0
投票

下面的两个代码块都应该为您工作。

第一个使用subset(),就像您最初尝试的那样:

new_df <- left_join(df2, df1, by = "ID") %>%
  subset(as.Date(Start Date, "%m-%d-%Y") > as.Date(START_DT, "%m-%d-%Y") & as.Date(End Date, "%m-%d-%Y") <= as.Date(END_DT, "%m-%d-%Y"))

第二个使用filter()

new_df <- left_join(df2, df1, by = "ID") %>%
  filter(as.Date(Start Date, "%m-%d-%Y") > as.Date(START_DT, "%m-%d-%Y") & as.Date(End Date, "%m-%d-%Y") <= as.Date(END_DT, "%m-%d-%Y"))

我希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.