[英]Replace Values in Dataframe Column based on match in second data frame columns
I've seen a half dozen or so solutions to this on Stack Overflow, but, all dealing with matches within a single data frame using 'within'. 我已经在Stack Overflow上看到了六种左右的解决方案,但是,所有解决方案都使用“内”来处理单个数据帧中的匹配。 I need a solution that goes across multiple dataframes:
我需要一个跨多个数据框的解决方案:
I have values in a column in Data Frame 1 我在数据框1的一列中有值
DF1$A
: "1, 2, 1, 3, 2, 6, 4, 5, 8, 8, 2, 7, 4, etc."DF1$A
:“DF1$A
等。”
I have a second data frame with the 'key' to these codes 我还有第二个数据框,其中包含这些代码的“键”
DF2$A
: "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"DF2$A
:“ 1、2、3、4、5、6、7、8、9、10”
DF2$B
: "Pie, Pizza, Hamburgers, etc."DF2$B
:“馅饼,比萨饼,汉堡包等”
How do I change the values in DF1$A
to match the values in DF2$B
? 如何更改
DF1$A
中的值以匹配DF2$B
中的值?
You can do this with match
as a pointer to specific positions in df2$B
: 您可以使用
match
作为指向df2$B
特定位置的指针来执行此操作:
# make some toy data
set.seed(1)
df1 <- data.frame(A = sample(seq(3), 10, replace = TRUE))
df2 <- data.frame(A = seq(3), B = c("pizza", "hot dog", "hamburger"), stringsAsFactors = FALSE)
df1$B <- df2$B[match(df1$A, df2$A)]
Result: 结果:
> df1
A B
1 3 hamburger
2 1 pizza
3 2 hot dog
4 1 pizza
5 1 pizza
6 2 hot dog
7 1 pizza
8 2 hot dog
9 3 hamburger
10 2 hot dog
You can use base merge
to join by the index, and select
from dplyr
to subset and rename: 您可以使用基本
merge
按索引dplyr
,然后从dplyr
select
子集并重命名:
library(tidyverse)
DF1 <- DF1 %>%
merge(DF2, by = "A") %>%
select(-A, A = B)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.