R update function, how to drop all the variables that are related to a pre-specified variable

前端 未结 1 1439
盖世英雄少女心
盖世英雄少女心 2021-01-16 05:46

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

相关标签:
1条回答
  • 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
    
    0 讨论(0)
提交回复
热议问题