R中使用case_when分类腰围变量返回错误值问题排查
解决case_when按性别分类腰围的问题
问题分析
你遇到的核心问题是Sex=2且Waist_C=94的记录未被正确分类为"high",大概率是条件逻辑组织不当或变量类型不匹配导致的。
修正后的代码
推荐用嵌套case_when的方式,先按性别分组再判断腰围区间,逻辑更清晰,不易出错:
data_norm <- data_norm %>% mutate( Waist_C_Classification = case_when( # 男性(Sex=1)的腰围分类 Sex == 1 ~ case_when( Waist_C < 94 ~ "low", Waist_C <= 102 ~ "medium", TRUE ~ "high" # 捕获所有剩余情况 ), # 女性(Sex=2)的腰围分类 Sex == 2 ~ case_when( Waist_C < 80 ~ "low", Waist_C <= 88 ~ "medium", TRUE ~ "high" # 捕获所有剩余情况 ), # 处理性别非1/2的异常情况 TRUE ~ NA_character_ ) )
额外检查项
- 变量类型验证:用
str(data_norm)确认Sex和Waist_C的类型。如果Waist_C是字符型,先转成数值:data_norm <- data_norm %>% mutate(Waist_C = as.numeric(Waist_C)) - 条件拼写检查:确保所有相等判断用
==而非赋值符号=,数值阈值(如88、94等)没有写错。 - 数据值检查:确认目标记录的
Sex确实为2,Waist_C确实为94(而非类似84的笔误)。
内容的提问来源于stack exchange,提问作者Esther González
相关产品推荐
相关产品推荐

