0

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.

Navya
  • 307
  • 3
  • 15

2 Answers2

0

If 2 data frames have a common column, you should join them, see this article.

Otherwise, just do

df1$new_col <- df2$some_col

Remeber, R is vector-based.

Thomas Jc
  • 137
  • 2
0

Use merge: d1 <- merge(x = d1, y = d2[, c("col1","col2","col3","col4","col5")], by = c("col1","col2","col3","col4"), all.x = TRUE)

Tur
  • 604
  • 4
  • 9
  • d2 can have more than d1 rows . I don't want to merge but add col5 from d2 where those conditions are satisfied. – Navya Apr 13 '20 at 10:56
  • Answer edited, there is no problem merging them with all.x = TRUE, it will not add more rows to d1. If there is any case in d1 not in d2 it will add NA although – Tur Apr 13 '20 at 11:13
  • ,I edited my question please, suggest me how to get the values like described above? – Navya Apr 13 '20 at 19:03