Home > other >  Data not recognized inside the function in R
Data not recognized inside the function in R

Time:11-27

I wonder why my data123 is not recognized inside the allEffects(fit2, ...) call below? Is there a fix to this?

My "R version 4.0.0 (2020-04-24)", windows 10 machine.

Error object 'data123' not found

library(effects)

m1 <- lm(mpg ~ hp   cyl, data = mtcars)


foo <- function(fit,...) {
   
   data123 <- eval(fit$call$data)
   
   fit2 <- lm(fit$call$formula, data = data123)
      
   allEffects(fit2, ...)   #### 'data123' not recognized HERE  
}   
#----------EXAMPLE OF USE:
foo(m1)

# Error during wrapup: object 'data123' not found

CodePudding user response:

The allEffects function is very picky about environments. You need to make sure the dataset you want to use is in the same environment as the formula you use for the model. Try

foo <- function(fit,...) {
  
  data123 <- eval(fit$call$data)
  formula123 <- eval(fit$call$formula)
  environment(formula123) <- environment()
  
  fit2 <- lm(formula123, data = data123)
  
  allEffects(fit2, ...) 
}   
foo(m1)

Here we explicitly extract the formula and reset it's environment to the function's body which is where data123 is defined.

  • Related