我有以下两个数据帧:
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"