[SOLVED] Convert value of one df based on second df in R


I have 2 dataframe df1 and df2. df1 have 2 specific columns:

                                                    Code: H4, H5. 
                                                    Cat: 010121, 010190, 345654... 
                                                    and other variables too

df2 has 2 columns: V17 & V02. Both of these columns contains values, but V17 contains same values as Cat column in df1, but in different order.

V17       v02
010121    010110
010129    010190
010130    010190
.....     .....

What I need is following: if specific row of df1$code= H5, the observed value in Cat column must be changed by corresponding value in V02

For instance I we this kind of row in df1:

Code     Cat        ...
H4       010121     ...

010121 value must be change by 010110 (according to V02)

V17       v02
010121    010110

and I need all these for the rest of dataframe like a loop function.
Hope that’s not too complicate.


This is how I would proceed:

  1. Merge the table based on the common column (I’m assuming here that you Cat and V17 columns contain unique values?)

df3 <- merge(df1, df2, by.x = "Cat", by.y = "V17")

  1. Assign to Cat the value of V02 if Code = H5

df3$Cat <- ifelse(df3$Code == "H5", df3$V02, df3$Cat)

I cannot test the code without a reproducible example but hopefully this can help somehow.

Good luck !

Answered By – Timelate

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *