You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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()`:

我原本认为这段代码可以正常运行,因为之前用过相同的表达式且未出现错误。


问题分析与修复

  1. 拼写错误:条件中的Disgree是拼写错误,正确应为Disagree,错误拼写会导致该选项无法被匹配,触发case_when分支不完整的错误。
  2. 默认分支写法错误:case_when不需要提前定义ELSE <- TRUE,自定义的ELSE变量无法被识别为默认匹配条件,直接用TRUE ~ 结果作为默认分支即可。
  3. 类型不一致:返回的"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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:35:24