我有一个带有2个变量的数据框:
Correct FACE.RESP
1 1 1
2 2 1
3 1 2
4 2 2
5 2 2
6 2 1
我想重新编码/替换'FACE.RESP'列中的值,如果'FACE.RESP'中的值与'Correct'中的值匹配,则'FACE.RESP'中的值应为重写为1。如果'FACE.RESP'中的值与'Correct'中的值不匹配,则'FACE.RESP'中的值应重新编码为0。
我尝试使用mutate和case_when以下代码:
mutate(FACE.RESP = case_when(FACE.RESP == Correct ~ '1', FACE.RESP <= Correct ~ '0', FACE.RESP >= Correct ~ '1'))
但是结果是这样的:
Correct FACE.RESP
5 2 2
6 2 1
7 1 NA
8 2 NA
9 2 NA
10 1 NA
有人可以建议如何实现所需的结果,并解释上述代码行有什么问题吗?
您只需要检查FACE.RESP
和Correct
值相同的一种情况,并将所有其他值分配为0。
library(dplyr)
df %>% mutate(FACE.RESP = case_when(FACE.RESP == Correct ~ 1,TRUE ~ 0))
# Correct FACE.RESP
#1 1 1
#2 2 0
#3 1 0
#4 2 1
#5 2 1
#6 2 0
但是,更简单的方法是比较两列,并在开始时使用+
将逻辑值转换为整数值。
df$FACE.RESP <- +(df$Correct == df$FACE.RESP)
数据
df <- structure(list(Correct = c(1L, 2L, 1L, 2L, 2L, 2L), FACE.RESP = c(1L,
1L, 2L, 2L, 2L, 1L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
我们可以使用as.integer
df$FACE.RESP <- as.integer(df$Correct == df$FACE.RESP)
df <- structure(list(Correct = c(1L, 2L, 1L, 2L, 2L, 2L), FACE.RESP = c(1L,
1L, 2L, 2L, 2L, 1L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
这里是另一个dplyr
解决方案。
library(dplyr)
df %>% mutate(FACE.RESP = +(Correct == FACE.RESP))
# Correct FACE.RESP
#1 1 1
#2 2 0
#3 1 0
#4 2 1
#5 2 1
#6 2 0