首页 > 解决方案 > 如何在R中比较两个变量列?

问题描述

我是 R 新手,需要帮助!我有很多变量,包括 Response 和 RightResponse。我需要比较这两列,并创建一个新列来显示每个值对之间是否存在匹配或缺失。谢谢。

标签: rrstudiodata-analysis

解决方案


也许是这样的?

library(magrittr)
library(dplyr)

> res <- data.frame(Response=c(1,4,4,3,3,6,3),RightResponse=c(1,2,4,3,3,6,5))
> res <- res %>% mutate("CorrectOrNot" = ifelse(Response == RightResponse, "Correct","Incorrect"))
> res

  Response RightResponse CorrectOrNot
1        1             1      Correct
2        4             2    Incorrect
3        4             4      Correct
4        3             3      Correct
5        3             3      Correct
6        6             6      Correct
7        3             5    Incorrect

基本上,mutate 函数创建了一个新列,其中包含 Response 和 RightResponse 之间的比较结果。

希望这可以帮助!


推荐阅读