如何根据查找匹配多列 table
How to match multiple columns based on lookup table
我有以下两个数据框:
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 列并找到 ids(此处:"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"
您可以使用 apply
和 match
根据查找 table.
匹配多个列
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)]))
我有以下两个数据框:
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 列并找到 ids(此处:"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"
您可以使用 apply
和 match
根据查找 table.
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)]))