小编use*_*478的帖子

如何基于多列和条件进行模糊连接?

我正在尝试左连接两个数据框(df1、df2)。数据框共有两列:区域和斜率。区域是一个因子列,斜率是数字。

    df1 = data.frame(slope = c(1:6), zone = c(rep("Low", 3), rep("High", 3)))
    df2 = data.frame(slope = c(2.4, 2.4,6.2), zone = c(rep("Low", 1), rep("High", 2)), other = c(rep("a", 1), rep("b", 1), rep("c", 1)))
    df1
    df2
Run Code Online (Sandbox Code Playgroud)

我想加入数据框,以便它们首先在区域上完全匹配,然后是斜率最接近的匹配。如果有两个等距的斜率值,只要一致地应用规则并且不会导致重复的行,连接是向上还是向下舍入都没有关系。

我更喜欢用fuzzy_join 或dplyr 而不是data.table 来做到这一点。

结果应该类似于:

    df3 = data.frame(slope = c(1:6), zone = c(rep("Low", 3), rep("High", 3)), other = c(rep("a", 3), rep("b",1), rep("c",2)))
    df3
Run Code Online (Sandbox Code Playgroud)

其中“other”的值首先由区域确定,然后是最近的斜率。

我试过了:

    distance_left_join(df, df2, by=c("zone"= "zone", "slope"="slope"))
Run Code Online (Sandbox Code Playgroud)

以及其他类型的模糊连接,但我认为它们可能不起作用,因为列的类型不同。我怀疑有一个fuzzy_left_join 解决方案,但我不明白如何创建匹配函数。

r fuzzyjoin

6
推荐指数
1
解决办法
884
查看次数

标签 统计

fuzzyjoin ×1

r ×1