我想对一个变量进行滚动连接,但要考虑对另一个变量的精确匹配。
我可以通过这种方式进行滚动加入:
library(data.table)
dt1 <- data.table(id1 = 1:4, foo = c("a","b","a","b"), val1 = c(10,20,30,34))
dt2 <- data.table(id2 = 1:4, foo = c("a","b","a","b"), val2 = c(15,25,35,45))
dt1
#> id1 foo val1
#> 1: 1 a 10
#> 2: 2 b 20
#> 3: 3 a 30
#> 4: 4 b 34
dt2
#> id2 foo val2
#> 1: 1 a 15
#> 2: 2 b 25
#> 3: 3 a 35
#> 4: 4 b 45
dt2[,val1:=val2]
dt2[dt1, on = .(val1), roll = -Inf]
#> id2 foo val2 val1 id1 i.foo
#> 1: 1 a 15 10 1 a
#> 2: 2 b 25 20 2 b
#> 3: 3 a 35 30 3 a
#> 4: 3 a 35 34 4 b
但是如果我也想匹配foo
怎么办?
我想要的输出如下:
#> id2 foo val2 val1 id1
#> 1: 1 a 15 10 1
#> 2: 2 b 25 20 2
#> 3: 3 a 35 30 3
#> 4: 4 b 45 34 4
这行不通:
dt2[dt1, on = .(val1, foo), roll = -Inf]
#> id2 foo val2 val1 id1
#> 1: NA a NA 10 1
#> 2: NA b NA 20 2
#> 3: NA a NA 30 3
#> 4: NA b NA 34 4