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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:07:25