Skip to content

Instantly share code, notes, and snippets.

@jwdink
Last active October 25, 2015 16:14
Show Gist options
  • Save jwdink/ac9b7819384dbcc7e7b2 to your computer and use it in GitHub Desktop.
Save jwdink/ac9b7819384dbcc7e7b2 to your computer and use it in GitHub Desktop.
Take a data frame and some columns, return copy of data frame with centered version of those columns (with 'C' appended to colnames)
center_predictors = function(data, predictors) {
if (!require('dplyr')) stop("Dplyr required")
require('lazyeval')
dots = list()
for (i in seq_along(predictors)) {
name = paste0(predictors[i], "_C")
if (is.factor(data[[predictors[i]]])) {
if (length(levels(data[[predictors[i]]])) > 2) stop("'", predictors[i], "' is a factor with more than 2 levels, cannot center.")
message("'", predictors[i], "' is a factor, will convert so that '", levels(data[[predictors[i]]])[2], "' will be 'positive'.")
} else if (is.character(data[[predictors[i]]])) {
stop("'", predictors[i], " is character, unsure how to center. Please convert to nummeric or factor.")
}
dots[[name]] = interp(~as.numeric(PRED) - mean(as.numeric(PRED), na.rm = TRUE), PRED = as.name(predictors[i]))
}
data %>%
ungroup() %>%
mutate_(.dots = dots)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment