Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Values in Dataframe Column based on match in second data frame columns

Tags:

r

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'. I need a solution that goes across multiple dataframes:

I have values in a column in Data Frame 1

DF1$A: "1, 2, 1, 3, 2, 6, 4, 5, 8, 8, 2, 7, 4, etc."

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$B: "Pie, Pizza, Hamburgers, etc."

How do I change the values in DF1$A to match the values in DF2$B ?

like image 844
RickGrimesOfAlexandria Avatar asked Mar 05 '17 19:03

RickGrimesOfAlexandria


1 Answers

You can do this with match as a pointer to specific positions in 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
like image 102
ulfelder Avatar answered Sep 24 '22 09:09

ulfelder