6

I have the following two dataframes:

>df1<-data.frame(A=c(0,0,0),B=c(0,201,0),C=c(0,467,0))
  A   B   C
1 0   0   1
2 0 201 467
3 0   0   0

>df2<-data.frame(A=c(201,467),B=c('abc','def'))
    A   B
1 201 abc
2 467 def

I would like to replace the values in df1 using matching "B" values in df2, creating a dataframe that looks like this:

   A   B   C
1 NA  NA  NA
2 NA abc def
3 NA  NA  NA

I can accomplish this on a column by column basis using the following code:

>df2$B[match(df1$B,df2$A)]

Unfortunately, I am working with a massive dataset and would therefore prefer to match all of the columns at once. Any help would be much appreciated.

2 Answers 2

3

You can do:

df1[] <- setNames(df2$B, df2$A)[as.character(unlist(df1))]
Sign up to request clarification or add additional context in comments.

Comments

2

Another possible solution:

df1<-data.frame(A=c(0,0,0),B=c(0,201,0),C=c(0,467,0))
df2<-data.frame(A=c(201,467),B=c('abc','def'))

library(qdap)
apply(df1, 2, lookup, df2)

## > apply(df1, 2, lookup, df2)
##      A  B     C    
## [1,] NA NA    NA   
## [2,] NA "abc" "def"
## [3,] NA NA    NA

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.