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)
CodePudding user response:
Use match
. By default, if there is no match, it returns NA
, indexing on NA
returns NA for 'C' as well
df1$D <- with(df1, C[match(B, A)])
-output
> df1
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
data
df1 <- structure(list(A = c("a", "b", "c", "d", "e", "f"), B = c("f",
"a", "b", "c", "e", "d"), C = c(12L, 23L, 33L, 1L, 11L, 55L),
D = c(55L, 12L, 23L, 33L, 11L, 1L)), class = "data.frame", row.names = c(NA,
-6L))
CodePudding user response:
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