R vlookup 结合 if...and

R vlookup combinded with if...and

作为 R 的初学者,我遇到了一个复杂的问题。

当 data$Date 为 between/exactly lookup$Begin 和 lookup$End 时,我想添加一个带有“1”的新列。 Identification_no 是两个数据集的键。 如果 data$date 不在 lookup$Begin 和 lookup$End 之间,那么新数据列中应该有一个“0”。

两个数据框的观察长度不同。

这是我的基本数据框:

> data
# A tibble: 6 x 2
  Date       Identification_no
* <date>                 <dbl>
1 2018-08-25                13
2 2018-02-03                54
3 2018-09-01                31
4 2018-11-10                54
5 2018-08-04                60
6 2018-07-07                58

这是我的查找数据框:

> lookup
# A tibble: 6 x 3
  Begin      End        Identification_no
* <date>     <date>                 <dbl>
1 2017-01-26 2017-01-26                53
2 2017-01-26 2017-01-26                53
3 2017-01-26 2017-01-26                53
4 2017-01-26 2017-01-26                53
5 2017-01-26 2017-01-26                53
6 2017-01-26 2017-01-26                53

提前感谢您的意见。


编辑:新样本数据

> data
# A tibble: 6 x 2
  Date       Identification_no
  <date>                 <dbl>
1 2018-08-25                13
2 2018-02-03                54
3 2018-09-01                31
4 2018-11-10                54
5 2018-08-04                60
6 2018-07-07                58

> lookup
# A tibble: 6 x 3
  Begin      End        Identification_no
  <date>     <date>                 <dbl>
1 2018-08-20 2018-08-27                13
2 2018-09-01 2018-09-08                53
3 2018-01-09 2018-01-23                20
4 2018-10-16 2018-10-30                 4
5 2017-12-22 2017-12-29                54
6 2017-10-31 2017-11-07                66

通过下面描述的方法得到的结果:

> final
        Begin        End Identification_no match_col
1: 2018-08-25 2018-08-25                13         1
2: 2018-02-03 2018-02-03                54         0
3: 2018-09-01 2018-09-01                31         0
4: 2018-11-10 2018-11-10                54         0
5: 2018-08-04 2018-08-04                60         0
6: 2018-07-07 2018-07-07                58         0

工作得很好 - 感谢您的解决方案。

此致, 保罗

可以做到:

library(data.table)

setDT(data)[, Date := as.Date(Date)]
setDT(lookup)[, `:=` (Begin = as.Date(Begin), End = as.Date(End), match_col = 1)]

final <- unique(lookup, by = c("Begin", "End","Identification_no"))[
  data, on = .(Begin <= Date, End >= Date, Identification_no)][
  is.na(match_col), match_col := 0]

在您的示例数据集上,这将给出:

final

        Begin        End Identification_no match_col
1: 2018-08-25 2018-08-25                13         0
2: 2018-02-03 2018-02-03                54         0
3: 2018-09-01 2018-09-01                31         0
4: 2018-11-10 2018-11-10                54         0
5: 2018-08-04 2018-08-04                60         0
6: 2018-07-07 2018-07-07                58         0

..但只是因为真的没有匹配。