加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

函数工作(boot.stepAIC)但在另一个函数 – 环境问题中引发错误?

发布时间:2020-12-18 00:05:35 所属栏目:安全 来源:网络整理
导读:我今天在R代码中意识到了一种奇怪的行为. 我尝试了一个包{boot.StepAIC},其中包含一个用于AIC逐步回归结果的bootstrap函数.但是我认为统计背景不是问题(我希望如此). 我可以使用R顶层的函数.这是我的示例代码. require(MASS)require(boot.StepAIC)n-100x-rno
我今天在R代码中意识到了一种奇怪的行为.
我尝试了一个包{boot.StepAIC},其中包含一个用于AIC逐步回归结果的bootstrap函数.但是我认为统计背景不是问题(我希望如此).
我可以使用R顶层的函数.这是我的示例代码.
require(MASS)
require(boot.StepAIC)

n<-100
x<-rnorm(n); y<-rnorm(n,sd=2); z<-rnorm(n,sd=3); res<-x+y+z+rnorm(n,sd=0.1)
dat.test<-as.data.frame(cbind(x,y,z,res))
form.1<-as.formula(res~x+y+z)
boot.stepAIC(lm(form.1,dat.test),dat.test) # should be OK - works at me

但是,我想把它包装在一个自己的函数中.我将数据和公式传递给该函数.但我在boot.stepAIC()中遇到错误:

the model fit failed in 100 bootstrap samples Error in
strsplit(nam.vars,“:”) : non-character argument

# custom function
fun.boot.lm.stepAIC<-function(dat,form) {
  if(!inherits(form,"formula")) stop("No formula given")
  fit.lm<-lm(formula=form,data=dat)
  return(boot.stepAIC(object=fit.lm,data=dat))
 }
fun.boot.lm.stepAIC(dat=dat.test,form=form.1)
# results in an error

那错误在哪里?我想它必须与当地和全球环境有关,不是吗?

解决方法

使用 anova test fails on lme fits created with pasted formula中的do.call提供了答案.

boot.stepAIC在函数内运行时无权访问表单;可以像这样在全球环境中重建;我们看到lm使用form.1作为公式,并且删除它使boot.stepAIC失败.

> form.1<-as.formula(res~x+y+z)
> mm <- lm(form.1,dat.test)
> mm$call
lm(formula = form.1,data = dat.test)
> rm(form.1)
> boot.stepAIC(mm,dat.test)
# same error as OP

使用do.call确实有效.在这里我也使用as.name;否则mm对象会携带整个数据集,而不仅仅是它的名称.

> form.1<-as.formula(res~x+y+z)
> mm <- do.call("lm",list(form.1,data=as.name("dat.test")))
> mm$call
lm(formula = res ~ x + y + z,dat.test)

要将此应用于原始问题,我会这样做:

fun.boot.lm.stepAIC<-function(dat,"formula")) stop("No formula given")
  mm <- do.call("lm",list(form,data=as.name(dat)))
  do.call("boot.stepAIC",list(mm,data=as.name(dat)))
}    
form.1<-as.formula(res~x+y+z)
fun.boot.lm.stepAIC(dat="dat.test",form=form1)

这也有效,但整个数据集都包含在最终输出对象中,最终输出也包含在控制台中.

fun.boot.lm.stepAIC<-function(dat,data=dat))
  boot.stepAIC(mm,data=dat)
}    
form.1<-as.formula(res~x+y+z)
fun.boot.lm.stepAIC(dat=dat.test,form=form.1)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读