【问题标题】:How to match multiple columns based on lookup table如何根据查找表匹配多个列
【发布时间】:2019-12-03 11:42:32
【问题描述】:

我有以下两个数据框:

lookup <- data.frame(id = c("A", "B", "C"),
                     price = c(1, 2, 3))

results <- data.frame(price_1 = c(2,2,1),
                      price_2 = c(3,1,1))

我现在想遍历results 的所有列,并将lookup 中的相应匹配id 添加为新列。所以我首先要获取 price_1 列并找到 ID(此处为:“B”、“B”、“A”)并将其作为新列添加到 results,然后我想对 price_2 执行相同操作列。

我的实际案例需要匹配 20 多列,因此我想避免硬编码的手动解决方案,并正在寻找一种动态方法,最好是在 tidyverse 中。

results <- results %>%
  left_join(., lookup, by = c("price_1" = "id")

将为我提供第一列的手动解决方案,我可以对第二列重复此操作,但我想知道是否可以为我的所有 results 列自动执行此操作。

预期输出:

price_1 price_2 id_1 id_2
2       3       "B"  "C"
2       1       "B"  "A"
1       1       "A"  "A"

【问题讨论】:

    标签: r merge lookup


    【解决方案1】:

    我们可以直接unlist 数据框和match

    new_df <- results
    names(new_df) <- paste0("id", seq_along(new_df))
    new_df[] <- lookup$id[match(unlist(new_df), lookup$price)]
    cbind(results, new_df)
    
    #  price_1 price_2 id1 id2
    #1       2       3   B   C
    #2       2       1   B   A
    #3       1       1   A   A
    

    dplyr,我们可以做

    library(dplyr)
    bind_cols(results, results %>%  mutate_all(~lookup$id[match(., lookup$price)]))
    

    【讨论】:

    • Nice.The dplyr 解决方案在我的情况下甚至比 @GKi 的解决方案快约 30 倍。这并不重要,因为我们谈论的是毫秒,但对于具有 10k+ 行的大型数据集可能更相关。
    【解决方案2】:

    您可以使用applymatch根据查找表匹配多个列

    cbind(results, t(apply(results, 1, function(i) lookup[match(i, lookup[,2]),1])))
    #  price_1 price_2 1 2
    #1       2       3 B C
    #2       2       1 B A
    #3       1       1 A A
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      相关资源
      最近更新 更多