Last active
February 16, 2016 13:13
-
-
Save alekrutkowski/3b35ce83f5806a7dc3c7 to your computer and use it in GitHub Desktop.
Convert an R data.frame with factors into a data.frame with dummies (non-factor columns unchanged)
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(magrittr) | |
factorsToDummies <- function(df) | |
# df: a data.frame. | |
# returns: a data.frame with non-factor columns unchanged | |
# and factor columns replaced by a series of dummies | |
# for each factor. | |
lapply(df, | |
function(x) | |
if (x %>% is.factor %>% not) x else | |
lapply(levels(x), | |
function(y) (x==y) %>% | |
as.numeric)) %>% | |
as.data.frame %>% | |
set_names(lapply(names(df), | |
function(x) | |
if (df[[x]] %>% is.factor %>% not) x else | |
paste(x, '=', levels(df[[x]]))) %>% | |
unlist) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment