I want to check if values from column B exist in column A, and if yes and equal with the value in that row, create another column D, getting the value from column C (for the A on that row).
| A | B | C | D |
|---|---|---|---|
| a | f | 12 | 55 |
| b | a | 23 | 12 |
| c | b | 33 | 23 |
| d | c | 1 | 33 |
| e | e | 11 | 11 |
| f | d | 55 | 1 |
This is what I have, but it’s not working as it should as it is setting the value of D by just checking if the value exists in column A and not comparing them.
ifelse(df$B %in% df$A, df$C , NA)
>Solution :
You could also do:
transform(df1, D = setNames(C,A)[B])
A B C D
1 a f 12 55
2 b a 23 12
3 c b 33 23
4 d c 1 33
5 e e 11 11
6 f d 55 1