在函数内调用 glmulti 时未找到错误对象

Car*_*rlo 2 r function

我无法在自己的函数中使用 glmulti 包。

下面的代码是重现错误的简化示例:错误:找不到对象“poplrun”

这是data.frame在函数内创建的。在第二个例子中,它没有找到参数 l。

我认为问题与调用 glmulti 的环境有关。我找到了这个帖子

无法在自己的函数中将参数传递给函数

并尝试do.callsubstitute(poplrun)or一起使用,as.name("poplrun")但显然我错过了一些东西,因为它不起作用。我还发现这篇文章 在将模型公式传递给另一个函数时找不到对象错误

并试图确定公式中的环境(如您在我的第一个示例中所见),但该环境也不起作用。我真的很感激这方面的任何帮助,因为现在我正在尝试解决这个难题两天了......

谢谢堆!

示例 1

    set.seed(5)
    df1<-data.frame(Scenario=rep(LETTERS[1:2], each=10), 
                   Iteration=rep(1:10, 2), V1=rnorm(n=20, mean=0.5, sd=0.1))
    LookUpT<-data.frame(Scenario=rep(LETTERS[1:5]), SV1=1:5, SV2=6:10 )
    InteractRun<- function (
      param="V1" , 
      SVs=c("SV1", "SV2"),
      ic="aic",
      l=1 
      ) {
         poplrun<-df1
         require(plyr)
         poplrun<- join(poplrun, LookUpT, by = 'Scenario', type="left")
         xs<-paste(SVs, collapse="*") 
         .env<-environment() 
         formula<-as.formula(paste0(param, "~", xs), env=.env)
         require(betareg)
         require(glmulti)
         cand<-glmulti(formula, data=poplrun, method="d", level=l, 
         fitfunc=betareg,  na.action=na.omit)
         print(cand)
       }
       InteractRun()
Run Code Online (Sandbox Code Playgroud)

示例 2

    set.seed(5)
    df1<-data.frame(Scenario=rep(LETTERS[1:2], each=10), Iteration=rep(1:10, 2), 
            V1=round(rnorm(n=20, mean=20, sd=2))) 
    LookUpT<-data.frame(Scenario=rep(LETTERS[1:5]), SV1=1:5, SV2=6:10 ) 
    InteractRun<- function (
    param="V1" , 
    SVs=c("SV1", "SV2"), 
    fam="poisson",
    ic="aic",
    l=1 
    ) {
       poplrun<-df1
       require(plyr)
       poplrun<- join(poplrun, LookUpT, by = 'Scenario', type="left")
       xs<-paste(SVs, collapse="*") 
       formula<-as.formula(paste0(param, "~", xs)) # set up formula to be used  
       glm1<-glm(data=poplrun, formula, family=fam, na.action=na.omit)
       require(glmulti)
       cand<-glmulti(glm1, method="d", level=l,  na.action=na.omit)
       print(cand)
      }
     InteractRun()
Run Code Online (Sandbox Code Playgroud)

Car*_*rlo 5

我要回答我自己的问题……过了一会儿,我想出了如何解决这个问题。正在使用对 glmulti 的正确调用,do.call但不需要substitute()as.name()。在示例 1 中,调用应该是: cand <- do.call("glmulti", list(formula, data=poplrun, method="d", level=l, fitfunc=betareg, na.action=na.omit)) 在示例 2 中: cand <- do.call("glmulti", list(glm1, method="d", level=l, na.action=na.omit))