Skip to content

Instantly share code, notes, and snippets.

@lurodrigo
Created March 5, 2018 18:30
Show Gist options
  • Save lurodrigo/1be066fb55890d91ad88100ce9aef02f to your computer and use it in GitHub Desktop.
Save lurodrigo/1be066fb55890d91ad88100ce9aef02f to your computer and use it in GitHub Desktop.
Provides a convenient way to create dummy variables
# to-do: properly document it
library(tidyverse)
library(rlang)
dummify = function(.data, ..., .pattern = "{column}_{value}") {
cols = quos(...)
new_cols = imap(cols, function(quoted_expr, column) {
if (is_integer(column) || column == "") {
column = expr_text(quoted_expr) %>% str_sub(2) # removes the ~
values = .data[[column]] %>% unique
} else {
values = eval_tidy(quoted_expr)
}
vec = .data[[column]]
imap(values, function(real_value, value) {
if (is_integer(value) || value == "")
value = real_value
dummy_col = glue(.pattern)
.data %>%
transmute(!!sym(dummy_col) := as.integer(vec == real_value))
}) %>%
bind_cols
})
bind_cols(.data, new_cols)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment