I have two data frames. i want to write a while loop to check for match values and Replace. Eg. if item = item2 and Rep !=Rep2 then create a new column in df2 with Rep. else if item=item2 and Rep = Rep2 then check if Rep2 has another replacement in df1 by comparing Rep2 with all items in df1.
df1
Item Rep
1. A F
2. B G
3. C H
4. D
5. H I
6. F
7. E Y
df2
item2 Rep2
1. c H
2. A F
3. E Y
4. X Y
5. B W
My code that finds the common values and replaces it this. i want to put this code in a while loop to check if every match Rep2 has a new replacement in df2. is there an alternative approach to do this
library(sqldf)
wdf1<- sqldf("select
df2.*,
case
when Item = item2 and Rep = Rep2 then 'Match' # i want a loop to go back and check if Rep2 has another replacement in df1
when Item = item2 and Rep != rep2 then Rep
else 'Item no found'
end Rep3
from df2 left join df1 on Item = item2")
This is how the result should look like
item1 Rep2 Rep3
1. c H I
2. A F F
3. E Y Y
4. X Y not found
5. B W G
if Rep3 (acting as a new item2 in df2) matches an item in df1 but there's no Rep then Rep3 is the latest replacement.