首页 > 解决方案 > 估算数值和分类的缺失值,并在 R 中对分类值进行居中和缩放,但有例外

问题描述

我想估算数字缺失值的中位数和分类缺失值的模式,然后将所有分类值转换为虚拟变量,居中并缩放它们。但是,我不想转换客户 ID,也不想对它们进行中心化和缩放。你能帮我修复我的代码吗?

library(recipes)
train.recipe <- recipe(y ~., data = trainingdata) %>%
  step_medianimpute(all_numeric()) %>%
  step_modeimpute(all_nominal())
  step_dummy(all_nominal(), -all_outcomes(), - trainingdata$Customer_ID) %>%
    step_center(all_predictors(), -trainingdata$Customer_ID) %>%
    step_scale(all_predictors(), -trainingdata$Customer_ID)

train.recipe %>%
  prep() %>%
  bake(., data.clean) %>%
  glimpse()

标签: rdata-modelingpredictionmissing-datatraining-data

解决方案


在不知道您的数据框并假设客户 ID 是您不想转换的唯一变量的情况下,您可以简单地在转换之前先将 ID 转换为行名:

df %>%
  column_to_rownames("id") # to convert column to rownames

df %>%
  rownames_to_column("id") # to revert that

为此,客户 ID 必须是唯一的!


推荐阅读