我试图比较一列的内容是否与另一列的内容相同或不同。
Response <- c("Old", "New", "Old", "New")
Correct_answer <- c("New", "Old", "Old", "New")
comparison <- data.frame(Response, Correct_answer)
我试过了:
mutate(comparison, Resp_final = ifelse(grepl("Old", Response), "1",
ifelse(grepl("New", Response), "2", "")))
但它只检查“响应”列。如何比较“Response”和“Correct_answer”列并使用dplyr将结果输入一列?
谢谢!
答案 0 :(得分:4)
如果您唯一关心的是平等,那么简单的if_else
将会:
comparison %>% mutate(Resp_final = if_else(Response == Correct_answer, 1, 0))
但是如果你想比较它们是否相等而且如何它们是相等的,你可以用case_when
来做到这一点:
comparison %>%
mutate(Resp_final = case_when(
Response == Correct_answer & Response == "Old" ~ "1",
Response == Correct_answer & Response == "New" ~ "2",
TRUE ~ ""))
输出:
## Response Correct_answer resp_final
## 1 Old New
## 2 New Old
## 3 Old Old 1
## 4 New New 2