1

我在 data.table(DT1)中有一个列是递减计数(比如说pol_count),另一列是人口中的平均年龄(比如说AverageAge)。我正在尝试获取我的值pol_count(比如 400)和我的值AverageAge(比如 85),并将它们与名为FactorFile.

这是一瞥FactorFile

Count_Greater_Than  Age_Less_Than   Months  Factor
100                 80              12      1
85                  82              16      0.85
65                  84              20      0.65
45                  86              24      0.45

在这种情况下,pol_countis > 100 因此它将返回第三列的 ( Months) 值 12,并且AverageAgeis < 86 但 > 84 因此它将返回 20。然后我需要另一列来取最大值,所以最终答案是 20。最后,与 20 相关联的列Factor是 65%。

我不确定如何在不使用完全匹配的情况下加入表格。基本上我想要一个最后一个参数为 TRUE 的 VLOOKUP,将最接近的值拉到提供的查找值。

我试过使用包fuzzyjoin,这是我的声明。它运行,但我的 data.table 似乎没有发生任何事情:

fuzzy_left_join(DT1, FactorFile, by = c("AverageAge" = "Average_Age_Less_Than"), match_fun = `<=`)

关于如何正确使用模糊连接或更简单的方法来实现此连接的任何提示?总而言之,我试图在 DT1 中获取两列,并通过加入 FactorFile 将 Months 列和 Factor 列返回到 DT1。

谢谢!

4

1 回答 1

1

也许是这样的:

DT1[, c("M1", "F1") := 
    FactorFile[.SD, on=.(Count_Greater_Than=pol_count), roll=Inf, .(Months, Factor)]
]

DT1[, c("M2", "F2") := 
    FactorFile[.SD, on=.(Age_Less_Than=AverageAge), roll=Inf, .(Months, Factor)]
]

DT1[, c("M", "Fac") := {
        mm <- pmax(M1, M2)
        .(mm, fifelse(mm==M1, F1, F2))
    }]

输出:

   pol_count AverageAge M1 F1 M2   F2  M  Fac
1:       400         85 12  1 20 0.65 20 0.65

数据:

library(data.table)
DT1 <- data.table(pol_count=400, AverageAge=85)
FactorFile <- fread("
Count_Greater_Than  Age_Less_Than   Months  Factor
100                 80              12      1
85                  82              16      0.85
65                  84              20      0.65
45                  86              24      0.45")
于 2020-06-27T04:02:37.133 回答