r - 从数据框中的所有分类变量创建虚拟变量

标签 r tidyverse one-hot-encoding

我需要对数据框中的所有分类列进行一次编码。我发现了这样的东西:

one_hot <- function(df, key) {
  key_col <- dplyr::select_var(names(df), !! rlang::enquo(key))
  df <- df %>% mutate(.value = 1, .id = seq(n()))
  df <- df %>% tidyr::spread_(key_col, ".value", fill = 0, sep = "_") %>% 
  select(-.id)
}

但我不知道如何将它应用于所有分类列。

keys <- select_if(data, is.character)[-c(1:2)]
tmp <- map(keys, function(names) reduce(data, ~one_hot(.x, keys)))

抛出下一个错误

Error: var must evaluate to a single number or a column name, not a list

更新:

customers <- data.frame(
  id=c(10, 20, 30, 40, 50),
  gender=c('male', 'female', 'female', 'male', 'female'),
  mood=c('happy', 'sad', 'happy', 'sad','happy'),
  outcome=c(1, 1, 0, 0, 0))
customers

编码后

  id gender.female gender.male mood.happy mood.sad outcome
1 10             0           1          1        0       1
2 20             1           0          0        1       1
3 30             1           0          1        0       0
4 40             0           1          0        1       0
5 50             1           0          1        0       0

最佳答案

也是单线与 fastDummies 包。

fastDummies::dummy_cols(customers)

  id gender  mood outcome gender_male gender_female mood_happy mood_sad
1 10   male happy       1           1             0          1        0
2 20 female   sad       1           0             1          0        1
3 30 female happy       0           0             1          1        0
4 40   male   sad       0           1             0          0        1
5 50 female happy       0           0             1          1        0

关于r - 从数据框中的所有分类变量创建虚拟变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601564/

相关文章:

r - PowerShell:在大文件中替换NUL不起作用

r - 在 R 中映射/迭代不同大小的列表

python - 如何在 Scikit-learn 中获取 OneHotEncoder 的维度数

r - 通过 id R 查找时差

c++ - R 内部 : extracting a function pointer from an SEXP object

使用 map/ifelse/when 嵌入 xts 对象的 R purrr 数据操作

r - tidyverse 使用两种不同的 reshape 策略(创建 calcategorized 和 binary 列)执行ivot_wider

r - 仅使用 tidyverse 从 R 中每一行的唯一代码中提取某些字母

machine-learning - Keras 是否需要一种热编码?

python - 来自 sklearn 的 OneHotEncoder 在传递类别时给出 ValueError