Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Last active February 16, 2016 13:13
Show Gist options
  • Save alekrutkowski/3b35ce83f5806a7dc3c7 to your computer and use it in GitHub Desktop.
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)
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