Skip to content

Instantly share code, notes, and snippets.

@jrnold
Created April 15, 2017 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrnold/17c5333cbb721d64484cbfa1bf60fec2 to your computer and use it in GitHub Desktop.
Save jrnold/17c5333cbb721d64484cbfa1bf60fec2 to your computer and use it in GitHub Desktop.
Filtering terms and variables in R model formulas
f_filter_vars <- function(formula., ...) {
f_filter_vars_(formula., .dots = lazyeval::lazy_dots(...))
}
f_filter_vars_ <- function(formula., ..., .dots) {
dots <- lazyeval::all_dots(.dots, ...)
.terms <- terms(formula.)
.factors <- attr(.terms, "factors")
selectx <- dplyr::select_vars_(rownames(.terms), dots)
keepx <- as.logical(colSums(attr(ft, "factors")[selectx, , drop = FALSE]))
dropx <- seq_len(ncol(.factors))[!keepx]
# this will keep the environment of formula.
formula(drop.terms(.terms, dropx = dropx))
}
f_filter_terms <- function(formula., ...) {
f_filter_terms_(formula., .dots = lazyeval::lazy_dots(...))
}
f_filter_terms_ <- function(formula., ..., .dots) {
dots <- lazyeval::all_dots(.dots, ...)
.terms <- terms(formula.)
.factors <- attr(.terms, "factors")
selectx <- dplyr::select_vars_(colnames(.factors), dots)
keepx <- colnames(.factors) %in% selectx
dropx <- seq_len(ncol(.factors))[!keepx]
# this will keep the environment of formula.
formula(drop.terms(.terms, dropx = dropx))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment