首页 > 解决方案 > R 配方中的一种热编码仅因子变量

问题描述

我有一个df像这样的数据框

height  age  dept
69       18     A
44        8     B
72       19     B
58       34     C

我想只对因子变量进行一次热编码(只有 dept 是一个因子)。我怎样才能做到这一点?

目前我正在选择一切..

并收到此警告:

警告消息:以下变量不是因子向量,将被忽略:heightage

ohe <- df %>% 
    recipes::recipe(~ .) %>%
    recipes::step_dummy(tidyselect::everything()) %>%
    recipes::prep() %>%
    recipes::bake(df)

标签: rdplyr

解决方案


使用wherewithis.factor代替everything

library(dplyr)
df %>% 
    recipes::recipe(~ .) %>%
    recipes::step_dummy(tidyselect:::where(is.factor)) %>%
    recipes::prep() %>%
    recipes::bake(df)

-输出

# A tibble: 4 × 4
  height   age dept_B dept_C
   <int> <int>  <dbl>  <dbl>
1     69    18      0      0
2     44     8      1      0
3     72    19      1      0
4     58    34      0      1

数据

df <- structure(list(height = c(69L, 44L, 72L, 58L), age = c(18L, 8L, 
19L, 34L), dept = structure(c(1L, 2L, 2L, 3L), .Label = c("A", 
"B", "C"), class = "factor")), row.names = c(NA, -4L), class = "data.frame")

推荐阅读