I have 2 data frames i.e, d1 and d2. I want to add new column to d1 from d2 with multiple conditions. I have tried like below:
d1 dataframe is like below: Taking example to understand
col1 col2 col3 col4
user1 vt1 fc1 dt1
user2 vt2 fc2 dt2
user3 vt3 fc3 dt3
user4 vt4 fc4 dt4
d2 dataframe is like below : Taking example to understand
col1 col2 col3 col4 col5
user1 vt1 fc1 dt1 52
user2 vt2 fc2 dt2 34
user3 vt3 fc3 dt3 20
user4 vt4 fc4 dt4 17
user5 vt5 fc5 dt5 23
user6 vt6 fc6 dt6 45
I want to add col5 to d1. I have tried like below:
for(i in 1:nrow(d1)){
d1$t1[i] <- d2$col5[d1$col1[i] == d2$col1 &
d1$col2[i] == d2$col2 &
d1$col3[i] == d2$col3 &
d1$col4[i] == d2$col4 ]
}
Expected output:
col1 col2 col3 col4 col5
user1 vt1 fc1 dt1 52
user2 vt2 fc2 dt2 34
user3 vt3 fc3 dt3 20
user4 vt4 fc4 dt4 17
It is not giving error and not creating new column, Why? Where am missing the logic. Please, suggest me.
If any combination not found in d2 it should take value from another data frame d3 like below:
d3:
col1 col2 col3 col4
user1 vt1 fc1 12
user2 vt2 fc2 23
user3 vt3 fc3 35
user4 vt4 fc4 28
If d1 combination not found in d2 then it should take value from d3. How do i get that ?
Suppose if we do not get user3,vt3,fc3,dt3 not found then we should go for d3 combination i.e, user3,vt3,fc3 and get value corresponding to that i.e, 35.
Then Expected output should be:
d1:
col1 col2 col3 col4 col5
user1 vt1 fc1 dt1 52
user2 vt2 fc2 dt2 34
user3 vt3 fc3 dt3 35
user4 vt4 fc4 dt4 17
then 3rd row value is 35.
I want to get values like above.