Created
December 9, 2017 18:21
-
-
Save EmilHvitfeldt/3da33a5d03f94a31f4892c9f658295b0 to your computer and use it in GitHub Desktop.
One hot transformation of catagorical variable in tidyverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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