我们可以像这样使用 data.table 执行此操作,其中第一列是 table2$c1,第二列是对应的 table1$c1。
这里有一些数据:
set.seed(123)
library(data.table)
## this replaces your table1$c1
xx <- seq(0.0,99,0.1)
## choose 6 variable and add some offset ( 0.01 and -0.01)
y <- c(sample(xx,3) + 0.01 ,sample(xx,3) - 0.01)
data.table(c1 = xx, xx, key = "c1")[J(y),, roll = 'nearest', rollends = TRUE]
现在设置选项我们roll
得到nearest
:
data.table(c1 = xx, xx, key = "c1")[J(y),,
roll = 'nearest', rollends = TRUE]
c1 xx
1: 28.41 28.4
2: 78.01 78.0
3: 40.41 40.4
4: 87.49 87.5
5: 93.09 93.1
6: 4.49 4.5
xx 列是最接近 table$c1 的值。如果要设置距离,可以将滚动设置为 0.01/-0.01,如下所示:
data.table(c1 = xx, xx, key = "c1")[J(y),,
roll = 0.01, rollends = TRUE]
或者
data.table(c1 = xx, xx, key = "c1")[J(y),,
roll = -0.01, rollends = TRUE]