Skip to content

Instantly share code, notes, and snippets.

@nutterb
Created December 30, 2016 12:43
Show Gist options
  • Save nutterb/92cbd675b80ba184ac8788d5b6c2d847 to your computer and use it in GitHub Desktop.
Save nutterb/92cbd675b80ba184ac8788d5b6c2d847 to your computer and use it in GitHub Desktop.
Options for Creating Dummy Variables
library(magrittr)
dummy_ifelse <- function(x)
{
if (!is.factor(x)) stop("x is not a factor")
lev <- levels(x)
lapply(lev[-1],
function(l) ifelse(x %in% l, 1, 0)) %>%
setNames(lev[-1]) %>%
as.data.frame()
}
dummy_arith <- function(x)
{
if (!is.factor(x)) stop("x is not a factor")
lev <- levels(x)
lapply(lev[-1],
function(l) x %in% l + 0L) %>%
setNames(lev[-1]) %>%
as.data.frame()
}
dummy_list <- function(x)
{
if (!is.factor(x)) stop("x is not a factor")
lev <- levels(x)
lapply(lev[-1],
function(l)
{
y <- x
levels(y) <- list("1" = l,
"0" = levels(y)[!levels(y) %in% l])
as.numeric(as.character(y))
}) %>%
setNames(lev[-1]) %>%
as.data.frame()
}
library(microbenchmark)
microbenchmark(
ifelse = dummy_ifelse(iris$Species),
arith = dummy_arith(iris$Species),
list_m = dummy_list(iris$Species),
model_mat = model.matrix(~iris$Species) %>% as.data.frame
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment