Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing the content of two character columns with dplyr

Tags:

r

dplyr

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!

like image 996
Simon Avatar asked Jan 15 '17 14:01

Simon


1 Answers

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
like image 82
yeedle Avatar answered Oct 10 '22 11:10

yeedle