I have a R formula object:
formula1 <- y ~ x1 + x2 + x3 + x1:x2
I want to update this formula object by dropping all x1-related variabl
Here's a function to remove a term including all interactions in which the term is present:
remove_terms <- function(form, term) {
fterms <- terms(form)
fac <- attr(fterms, "factors")
idx <- which(as.logical(fac[term, ]))
new_fterms <- drop.terms(fterms, dropx = idx, keep.response = TRUE)
return(formula(new_fterms))
}
Apply the function:
formula1 <- y ~ x1 + x2 + x3 + x1:x2
# the term that should be removed
to_remove <- "x1"
remove_terms(formula1, to_remove)
# y ~ x2 + x3