I'm working with a dataset that has a structure I haven't worked with before. It has this format (code for data input at the end):
df
#> Instance Alice_prefers Bob_prefers Charlie_prefers
#> 1 1 Bob Charlie Alice
#> 2 2 Bob Alice Bob
#> 3 3 Bob Charlie Bob
I'm trying to create a variable that shows when two people "match", i.e. when they both prefer each other, eg if Alice prefers Bob, and Bob also prefers Alice--it's a mutual match: Alice and Bob match.
So my desired output is:
output
#> Instance Alice_prefers Bob_prefers Charlie_prefers Match
#> 1 1 Bob Charlie Alice <NA>
#> 2 2 Bob Alice Bob AliceBob
#> 3 3 Bob Charlie Bob BobCharlie
Using case_when() seems to do the trick, but is there an easier way than listing every single case, as I've started doing below? In my real dataset, I'll be looking to have many more people than just Alice, Bob and Charlie.
Second Question:
When I have more people, eg. Alice, Bob, Charlie, and Denise, the Match column may contain multiple matches (eg. Alice and Bob match, and Charlie and Denise match)--what's the tidy solution to this? Should I have an indicator variable for every single possible match, eg AliceBob, AliceCharlie, etc, that takes the value of 1 or 0?
The reason I'm doing this is: I would like to be able to quickly look at the number of matches and who is in the matches.
#df <- df %>% mutate(Match = ifelse(Alice_prefers=="Bob" & Bob_prefers =="Alice", "AliceBob", NA))
df <- df %>% mutate(
Match = case_when(
(Alice_prefers=="Bob" & Bob_prefers=="Alice") ~ "AliceBob",
(Charlie_prefers=="Bob" & Bob_prefers=="Charlie") ~ "BobCharlie"
)
)
df
Code for data input:
df <- data.frame(stringsAsFactors=FALSE,
Instance = c(1, 2, 3),
Alice_prefers = c("Bob", "Bob", "Bob"),
Bob_prefers = c("Charlie", "Alice", "Charlie"),
Charlie_prefers = c("Alice", "Bob", "Bob")
)