R语言中将收入变量0值重编码为NA的问题求助
R语言变量重编码问题解决方法
修正dplyr::case_when的用法
你的case_when代码有两个核心错误:
- 判断条件误用了赋值符号
=,应该用比较运算符== - 返回值类型不统一:
NA_real_是数值型,而后面的字符串是字符型,需统一使用字符型缺失值NA_character_
正确代码:
library(dplyr) Comm <- Comm %>% mutate(Income2 = case_when( Income1 == 0 ~ NA_character_, Income1 == 1 ~ 'Less than 50K', Income1 == 2 ~ 'More than 50K' ))
修正expss::recode的用法
expss的recode语法要求旧值在前、新值在后,你之前的标签定义格式错误,直接指定NA即可处理缺失值:
正确代码:
library(expss) Comm$Income2 <- recode(Comm$Income1, 0 ~ NA, 1 ~ 'Less than 50K', 2 ~ 'More than 50K' ) # 若需为变量添加标签属性(可选) Comm$Income2 <- labelled(Comm$Income2, c("Less than 50K" = 'Less than 50K', "More than 50K" = 'More than 50K'))
更简洁的factor转换方法
如果不需要复杂的条件判断,直接用factor()函数也能快速完成编码:
Comm$Income2 <- factor(Comm$Income1, levels = c(1, 2, 0), labels = c('Less than 50K', 'More than 50K', NA)) # 可选:移除NA对应的水平 Comm$Income2 <- droplevels(Comm$Income2)
内容的提问来源于stack exchange,提问作者Reap409
相关产品推荐
相关产品推荐

