I've got a data frame:
V1 V2 V3 V4 V5 V6 V7
a F B C D B A T
b R D C D F A T
c A C C R F A T
In every row I want to replace values in columns V3:V7 that matches column V2 with value in column V1. It should look like this.
V1 V2 V3 V4 V5
a C D F A T
b C R F A T
c A R F A T
How can I do this?
Here is another method using
lapply
:For each variable, matches are substituted using subsetting.
This same method may be used the the
replace
function:As with the solution of @mr-rip, these variables must be stored as character and not factor for this to work.
This also works with
data.table
:This should work as long as your data are strings and not factors:
Using a combination of
lapply
andifelse
, you can do:which gives:
Or:
which gives: