简体   繁体   English

根据第二个数据框列中的匹配替换“数据框列”中的值

[英]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.

相关问题 如何根据使用 R 与第三列的匹配,将数据框中多列的值替换为第二列中的值? - How do I replace values across multiple columns in a data-frame with values from a second column, based on a match with a third column using R? 根据另一个数据框的列值替换两个数据框列的值 - Replace the values of two dataframe columns based on the values of a column of another data frame 匹配另一列中的模式后替换数据框列中的值 - Replace values in columns of a data frame after match a pattern in another column R根据另一个数据框的精确匹配替换列的值 - R replace values of a column based on exact match of another data frame 根据列名称和变量匹配替换数据框中的单元格值 - Replace cell values in data frame based on column name and variable match 在R中,根据与第二个数据框中的值的近似数值匹配,创建/填充数据框中的一列 - In R, create/fill a column of a data frame based on an approximate numerical match to values in a second data frame 如果前两列都匹配,则将数据框的一列中的值添加到另一数据框的新列中 - adding values from one column of a data frame into a new column of another dataframe if the first two columns in both match 从基于两列的不同数据框中替换数据框中的 NA 值 - 就地 - - Replace NA values in a dataframe -- in place -- from a different data frame based on two columns 根据第二个数据框替换数据框中的列 - Replace column in data frames based on second data frame 根据第二列中的值将值移动到不同的列,XML 到 data.frame - Shifting values to different columns based on value in second column, XML to data.frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM