Reputation: 569
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.
Upvotes: 6
Views: 5734
Reputation: 110062
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
Upvotes: 2
Reputation: 89097
You can do:
df1[] <- setNames(df2$B, df2$A)[as.character(unlist(df1))]
Upvotes: 3