I have a dataframe like the one below:
df <- data.frame(a = c('x', 'y', 'z', 't', 'm'), b = c('x', 'x', 'y', NA, 'm'))
> df
a b
1 x x
2 y x
3 z y
4 t <NA>
5 m m
Now, for every value in both column 'a' and 'b' I want to see if it exists in any other row in both 'a' and 'b' and return a match. So, for row 1 I want to see if 'x' or 'y' exists in row 2:5 in either column a or b and then return 'TRUE'.
My desired result would then be:
> df$match = c(TRUE, TRUE, TRUE, FALSE, FALSE)
> df
a b match
1 x x TRUE
2 y x TRUE
3 z y TRUE
4 t <NA> FALSE
5 m m FALSE
Can't seem to figure out a way to do this. I've been trying to use dplyr:
df %>%
mutate(match = a %in% b | a %in% a | b %in% b | b %in% a)
but this just returns everything as TRUE. Furthermore if b is NA, then it will match to any other NA value aswell which is not intended.
Using rowwise operations also doesn't work, this just checks the value within the row.