【问题标题】:Data not recognized inside the function in RR中的函数内部无法识别数据
【发布时间】:2022-01-04 23:40:48
【问题描述】:

我想知道为什么我的data123 在下面的allEffects(fit2, ...) 调用中无法识别?有解决办法吗?

我的“R 版本 4.0.0 (2020-04-24)”,windows 10 机器。

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

【问题讨论】:

    标签: r dataframe function eval


    【解决方案1】:

    allEffects 函数对环境非常挑剔。您需要确保要使用的数据集与您用于模型的公式处于相同的环境中。试试

    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)
    

    在这里,我们显式提取公式并将其环境重置为定义 data123 的函数主体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2022-01-16
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      相关资源
      最近更新 更多