0

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.

  • 1
    I suspect this is a join/merge operation, and therefore can be resolved using https://stackoverflow.com/q/1299871/3358272 and/or https://stackoverflow.com/q/5706437/3358272. It's hard to tell without a reproducible question though. If the above do not answer your issue, please use `dput(.)` to share your data, see https://stackoverflow.com/q/5963269. Thanks! – r2evans Mar 22 '22 at 17:01
  • Please provide enough code so others can better understand or reproduce the problem. – Community Mar 23 '22 at 03:29

1 Answers1

0

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 !

Timelate
  • 138
  • 6