Reputation: 351
I need to one-encode all categorical columns in a dataframe. I found something like this:
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)
}
but I can't figure out how to apply it for all categorical columns.
keys <- select_if(data, is.character)[-c(1:2)]
tmp <- map(keys, function(names) reduce(data, ~one_hot(.x, keys)))
throws next error
Error:
var
must evaluate to a single number or a column name, not a list
upd:
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
after encoding
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
Upvotes: 5
Views: 6447
Reputation: 1047
Also one-liner with fastDummies
package.
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
Upvotes: 5
Reputation: 4989
One-liner with mltools
and data.table
:
one_hot(as.data.table(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
It one-hots all factor variables and has some nice features built in on how to handle NA`s and unused factor levels.
Upvotes: 0
Reputation: 6278
Here's an approach using the recipes
package.
library(dplyr)
library(recipes)
# Declares which variables are the predictors
recipe(formula = outcome ~ .,
data = customers) %>%
# Declare that one-hot encoding will be applied to all nominal variables
step_dummy(all_nominal(),
one_hot = TRUE) %>%
# Based on the previous declarations, apply transformations to the data
# and return the resulting data frame
prep() %>%
juice()
Upvotes: 2
Reputation: 816
Using the dummies
package:
library(dummies)
dummy.data.frame(customers)
id genderfemale gendermale moodhappy moodsad 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
Upvotes: 4