Say I have a data frame like the following:
mydf=data.frame(id=LETTERS, value=runif(26,0,1), match1=sample(c(0,1),26,replace=T), match2=sample(c(0,2),26,replace=T), match3=sample(c(0,3),26,replace=T), all_matches=sample(0:3,26,replace=T))
which looks like:
> mydf
id value match1 match2 match3 all_matches
1 A 0.267675256 1 0 0 0
2 B 0.974518682 1 0 3 3
3 C 0.175529131 1 2 3 0
4 D 0.050552174 0 2 0 0
5 E 0.228286981 0 0 0 1
6 F 0.025520208 0 2 3 1
7 G 0.206697937 1 2 0 2
8 H 0.644523511 0 2 3 2
9 I 0.342110147 0 0 3 3
10 J 0.430250450 1 0 0 1
...
match1 column has 0 and 1 values, match2 has 0 and 2 values, match3 0 and 3, and all_matches values from 0 to 3.
The only thing I want to do here is to rewrite 1, 2, and 3 values in those columns by a name associated to those values, and stored in another data frame:
match_df=data.frame(match=1:3, name=c('ABC','XYZ','IJK'))
which looks like this:
> match_df
match name
1 1 ABC
2 2 XYZ
3 3 IJK
What would be the best way to replace values 1, 2, 3 in columns match1, match2, match3, all_matches in mydf by names in match_df (leaving value 0 as NA)?
So far I'm merging match_df to each column of interest in mydf in a for loop, but I'm sure this can be done better in one line of code.
Any help appreciated! Thanks!