使用case_when配合mutate生成新变量时为何报错?
解决mutate中case_when报错的问题
我尝试用mutate修改一组变量,生成值已转换的新变量,代码如下:
ELSE <- TRUE Engagement_Master <- Engagement_Master %>% mutate(`My work gives me a sense of personal accomplishment%` = case_when( `My work gives me a sense of personal accomplishment` == "Strongly agree" ~ "1", `My work gives me a sense of personal accomplishment` == "Agree" ~ "1", `My work gives me a sense of personal accomplishment` == "Neither agree nor disagree" ~ "0", `My work gives me a sense of personal accomplishment` == "Disgree" ~ "0", `My work gives me a sense of personal accomplishment` == "Strongly disagree" ~ "0", ELSE ~ NA))
我一直收到如下错误:
Error in `mutate()`: ! Problem while computing `My work gives me a sense of personal accomplishment% = case_when(...)`. Caused by error in `case_when()`:
我原本认为这段代码可以正常运行,因为之前用过相同的表达式且未出现错误。
问题分析与修复
- 拼写错误:条件中的
Disgree是拼写错误,正确应为Disagree,错误拼写会导致该选项无法被匹配,触发case_when分支不完整的错误。 - 默认分支写法错误:case_when不需要提前定义
ELSE <- TRUE,自定义的ELSE变量无法被识别为默认匹配条件,直接用TRUE ~ 结果作为默认分支即可。 - 类型不一致:返回的"1""0"是字符型,而默认的
NA是逻辑型,类型不匹配会引发问题,需用NA_character_保持字符型一致。
修正后的代码
Engagement_Master <- Engagement_Master %>% mutate(`My work gives me a sense of personal accomplishment%` = case_when( `My work gives me a sense of personal accomplishment` == "Strongly agree" ~ "1", `My work gives me a sense of personal accomplishment` == "Agree" ~ "1", `My work gives me a sense of personal accomplishment` == "Neither agree nor disagree" ~ "0", `My work gives me a sense of personal accomplishment` == "Disagree" ~ "0", `My work gives me a sense of personal accomplishment` == "Strongly disagree" ~ "0", TRUE ~ NA_character_ ))
简化写法(可选)
用%in%合并相同结果的条件,让代码更简洁:
Engagement_Master <- Engagement_Master %>% mutate(`My work gives me a sense of personal accomplishment%` = case_when( `My work gives me a sense of personal accomplishment` %in% c("Strongly agree", "Agree") ~ "1", .default = "0" )) # 若需将未匹配值设为NA,替换.default为NA_character_
内容的提问来源于stack exchange,提问作者Karan Samtani
相关产品推荐
相关产品推荐

