如何根据查找表匹配多个列

我有以下两个数据帧:

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

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

我现在想遍历results的所有列,并从id中添加匹配的lookup作为新列。因此,我首先要获取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"
chenyu1644 回答:如何根据查找表匹配多个列

您可以使用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
,

我们可以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)]))
本文链接:https://www.f2er.com/2986208.html

大家都在问