我需要对数据框中的所有分类列进行单编码。我找到了以下类似的代码:
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)))
抛出下一个错误
错误:变量必须计算为单个数字或列名,而不是列表
更新:
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