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

在R中使用case_when重编码变量子集时报错的解决方案咨询

问题结论

不需要调整B列的格式,报错的核心原因是你误将不需要重编码的列纳入了转换范围,且重编码逻辑存在拼写错误。

报错原因
  • 你使用vars(c(1:4))选择了全部4列执行重编码,但B列是POSIXct格式的日期、A列是固定为"Y"的字符串,两类列都不需要参与李克特量表的数值转换。R在尝试将日期类的B列和字符串做相等判断时,无法完成格式转换,因此抛出报错。
  • 重编码逻辑中你将Strongly disagree拼写为Strongly disaagree,多了1个字母a,就算类型匹配,该选项也会匹配失败返回NA值。
修复方案

仅选择需要重编码的C、D列执行转换,同时修正拼写错误即可:

library(dplyr)
# 旧版dplyr使用mutate_at的写法
init2 <- df %>%
  mutate_at(vars(C, D), function(x) case_when( 
    x == "Neither agree nor disagree" ~ 3, 
    x == "Somewhat agree" ~ 4, 
    x == "Somewhat disagree" ~ 2,
    x == "Strongly agree" ~ 5,
    x == "Strongly disagree" ~ 1
  ))

如果你使用的是1.0.0及以上版本的dplyr,更推荐使用across的写法:

init2 <- df %>%
  mutate(across(c(C, D), ~case_when(
    .x == "Neither agree nor disagree" ~ 3, 
    .x == "Somewhat agree" ~ 4, 
    .x == "Somewhat disagree" ~ 2,
    .x == "Strongly agree" ~ 5,
    .x == "Strongly disagree" ~ 1
  )))

如果你需要批量处理所有字符类型的量表列,也可以通过类型判断筛选列,避免手动指定列名出错:

init2 <- df %>%
  mutate(across(where(is.character), ~case_when(
    .x == "Neither agree nor disagree" ~ 3, 
    .x == "Somewhat agree" ~ 4, 
    .x == "Somewhat disagree" ~ 2,
    .x == "Strongly agree" ~ 5,
    .x == "Strongly disagree" ~ 1,
    # 不匹配的字符值保留原值
    TRUE ~ .x
  )))

内容的提问来源于stack exchange,提问作者user2450223

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:39:00