在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
相关产品推荐
相关产品推荐

