I am trying to compare if the content of one column is equal or different from the content of another.
Response <- c("Old", "New", "Old", "New")
Correct_answer <- c("New", "Old", "Old", "New")
comparison <- data.frame(Response, Correct_answer)
I tried this:
mutate(comparison, Resp_final = ifelse(grepl("Old", Response), "1",
ifelse(grepl("New", Response), "2", "")))
But it only checks for the "Response" column. How can I compare both "Response" and "Correct_answer" columns and get the result in one column using dplyr?
Thanks!
If the only thing you care about is equality, then a simple if_else
will do:
comparison %>% mutate(Resp_final = if_else(Response == Correct_answer, 1, 0))
But if you want to compare not only whether they are equal but also how they are equal, you can do that with case_when
like so:
comparison %>%
mutate(Resp_final = case_when(
Response == Correct_answer & Response == "Old" ~ "1",
Response == Correct_answer & Response == "New" ~ "2",
TRUE ~ ""))
Output:
## Response Correct_answer resp_final
## 1 Old New
## 2 New Old
## 3 Old Old 1
## 4 New New 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With