update() inside a function only searches the global environment?

前端 未结 2 2142
半阙折子戏
半阙折子戏 2020-12-16 21:09

I tried to write a wrapper function to do likelihood ratio tests in batches. I tried to include update() to update the initial model. However, it seems that instead of looki

2条回答
  •  一个人的身影
    2020-12-16 21:22

    I've been bitten by this behaviour before too, so I wrote my own version of update. It evaluates everything in the environment of the formula, so it should be fairly robust.

    my_update <- function(mod, formula = NULL, data = NULL) {
      call <- getCall(mod)
      if (is.null(call)) {
        stop("Model object does not support updating (no call)", call. = FALSE)
      }
      term <- terms(mod)
      if (is.null(term)) {
        stop("Model object does not support updating (no terms)", call. = FALSE)
      }
    
      if (!is.null(data)) call$data <- data
      if (!is.null(formula)) call$formula <- update.formula(call$formula, formula)
      env <- attr(term, ".Environment")
    
      eval(call, env, parent.frame())
    }
    
    library(nlme4)
    
    fake <- data.frame(
      subj = rep(1:5, 4), 
      factor1 = rep(LETTERS[c(1,2,1,2)], each = 5), 
      factor2 = rep(letters[1:2], each = 10), 
      data = sort(rlnorm(20)))
    
    foo <- function() {
      temp <- fake
      model1 <- lmer(data ~ factor1 * factor2 + (1 | subj), fake)
      model1a <- my_update(model1, ~ . - factor1:factor2)
      model1a
    }
    foo()
    

提交回复
热议问题