6

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 ?

2 Answers 2

12

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can use base merge to join by the index, and select from dplyr to subset and rename:

library(tidyverse)

DF1 <- DF1 %>% 
  merge(DF2, by = "A") %>%
  select(-A, A = B) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.