r - 具有多个条件的左连接

标签 r merge

我有两个数据,我想用 2 个条件进行左连接。

Criteria 1 : Same Title

Criteria 2 : Date between StartDate & EndDate

数据B

Title  Date
A      2018-07-01
B      2019-12-30

数据A

Title StartDate  EndDate     Score
A     2018-01-01 2018-05-18    0
A     2018-05-19 2019-01-01    1
B     2019-10-01 2020-02-01    4
B     2020-02-02 2020-10-01    7

这就是我想要的

Title  Score
A       1
B       4

提前致谢!

最佳答案

我们可以对data.table使用非等值连接

library(data.table)
setDT(DataA)[DataB,  .(Title, Score), on = 
      .(Title, StartDate < Date, EndDate >= Date)]
#   Title Score
#1:     A     1
#2:     B     4

数据

DataA <- structure(list(Title = c("A", "A", "B", "B"), 
StartDate = structure(c(17532, 
17670, 18170, 18294), class = "Date"), EndDate = structure(c(17669, 
17897, 18293, 18536), class = "Date"), Score = c(0L, 1L, 4L, 
7L)), row.names = c(NA, -4L), class = "data.frame")

DataB <- structure(list(Title = c("A", "B"), Date = structure(c(17713, 
18260), class = "Date")), row.names = c(NA, -2L), class = "data.frame")

关于r - 具有多个条件的左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61717123/

相关文章:

Rstudio Git bash 每次 pop

R:在 map 上绘制圆形直方图/玫瑰图

algorithm - 合并线性列表 - 重建铁路网络

Git:将旧提交 merge 到当前头版本

r - 与基于多个非唯一列的替换合并

javascript - 递归合并排序函数错误: Cannot read property 'length' of undefined

r - 我可以假设总是可以在 R 中打开 pdf NULL 设备吗?

r - 在glmnet中绘制ROC曲线

mercurial - 无论如何自动 merge 或连接 hgtags (Mercurial)?

r - 访问 FUN 内的 lapply 索引名称