我在自己的函数中使用 glmulti 包时遇到问题。
下面的代码是重现错误的简化示例: 错误:找不到对象“poplrun”
这是在函数内创建的data.frame
。
在第二个示例中,它没有找到参数 l。
我认为问题与调用glmulti的环境有关。我找到了这篇文章
Trouble passing on an argument to function within own function
并尝试将 do.call
与 substitute(poplrun)
或 as.name("poplrun")
一起使用,但显然我是错过了一些东西,因为它不起作用。我也找到了这个帖子
Object not found error when passing model formula to another function
并尝试识别公式中的环境(正如您在我的第一个示例中看到的那样),但那个也不起作用。 我真的很感激任何帮助,因为现在我正在尝试解决这个难题两天......
谢谢!
示例 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()
示例 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()
最佳答案
我要回答我自己的问题...过了一会儿,我想出了如何解决这个问题。
对 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))
关于r - 在函数内调用 glmulti 时未找到错误对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699673/