Last active
October 25, 2015 16:14
-
-
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)
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
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