Skip to content

Instantly share code, notes, and snippets.

@EmilHvitfeldt
Created December 9, 2017 18:21
Show Gist options
  • Save EmilHvitfeldt/3da33a5d03f94a31f4892c9f658295b0 to your computer and use it in GitHub Desktop.
Save EmilHvitfeldt/3da33a5d03f94a31f4892c9f658295b0 to your computer and use it in GitHub Desktop.
One hot transformation of catagorical variable in tidyverse
library(tidyverse)
one_hot <- function(data, var) {
var_enquo <- enquo(var)
items <- data %>% pull(!!var_enquo)
items_unique <- items %>% unique()
out <- matrix(0, NROW(data), length(items_unique))
colnames(out) <- items_unique
for (i in items_unique) {
out[, i] <- items == i
}
data %>%
select(-!!var_enquo) %>%
bind_cols(as.tibble(out))
}
one_hot(iris, Species)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment