R语言ifelse匹配分位数表返回因子水平而非数值问题如何解决
问题原因
你代码里索引的是height_quantiles的第1列(height_quantiles[1,1]的第二个下标1对应第1列),该列是因子类型的salary_type,转换为数值后自然返回1、2、3的因子水平编码,你需要取存储目标数值的第2列quant_80。
解决方法
方法1:直接修正原ifelse代码
把索引的列从第1列改为第2列即可,也可以直接按列名索引,避免列顺序变动出错:
# 按列位置索引 test$height_pred = as.numeric(ifelse(test$salary_type == "A", height_quantiles[1,2], ifelse(test$salary_type == "B", height_quantiles[2,2], height_quantiles[3,2]))) # 更稳妥的按列名索引 test$height_pred = as.numeric(ifelse(test$salary_type == "A", height_quantiles[height_quantiles$salary_type=="A","quant_80"], ifelse(test$salary_type == "B", height_quantiles[height_quantiles$salary_type=="B","quant_80"], height_quantiles[height_quantiles$salary_type=="C","quant_80"])))
方法2:更简洁的匹配合并写法
嵌套ifelse在分类维度较多时维护成本很高,推荐用匹配或者左连接的方式实现,代码更简洁易读:
# 方法2.1 向量匹配,无需额外加载包 test$height_pred <- height_quantiles$quant_80[match(test$salary_type, height_quantiles$salary_type)] # 方法2.2 左连接,适合后续需要匹配多列值的场景 library(dplyr) test <- test %>% left_join(height_quantiles, by = "salary_type") %>% rename(height_pred = quant_80)
以上两种方法都可以直接得到你需要的3.75、3.71、4.12对应的数值结果,不需要额外做类型转换。
内容的提问来源于stack exchange,提问作者stats_noob
相关产品推荐
相关产品推荐

