试图tryCatch为我的功能

时间:2014-08-27 01:07:59

标签: r function for-loop data-fitting

我试图将此函数循环1000次并记录模型的系数 但有时当迭代超过50次时函数停止。如何让函数继续运行并记录时间失败?谢谢 我正在使用tryCatch(),但我不知道如何使它工作。 我如何计算1000次中有多少错误? 请帮忙

e0<-1:1000
emax<-1:1000
e50<-1:1000


 for (i in 1:1000)

{
rho=0.4
#5g

pre.5mg<-rnorm(n=50,mean=-0.5,sd=0.2)
x=0.4*rho-0.5
post.5mg<-rnorm(n=50,mean=pre.5mg*rho+x,sd=sqrt((0.3*0.3*(1-rho*rho))))
#25g
pre.25mg<-rnorm(n=50,mean=-0.5,sd=0.2) 
x25=0.4*rho-1
post.25mg<-rnorm(n=50,mean=pre.25mg*rho+x25,sd=sqrt((0.3*0.3*(1-rho*rho))))  
#100g
pre.100mg<-rnorm(n=50,mean=-0.5,sd=0.2)   
x100<-0.4*rho-1.2
post.100mg<-rnorm(n=50,mean=pre.100mg*rho+x100,sd=sqrt((0.3*0.3*(1-rho*rho))))
#250g
pre.250mg<-rnorm(n=50,mean=-0.5,sd=0.2)
x250<-0.4*rho-1.4
post.250mg<-rnorm(n=50,mean=pre.250mg*rho+x250,sd=sqrt((0.3*0.3*(1-rho*rho))))   




#response
Y<-c(post.5mg,post.25mg,post.100mg,post.250mg)
#dose
dose <- c(rep(10,50),rep(30,50),rep(120,50),rep(240,50))
w<-data.frame(Y,dose)

#MLE hyperbolic EMAX
abc=nls(formula=Y~e0+((dose*emax)/(dose+ed50)),start=c(e0=1000,emax=10000,ed50=20)
  ,data=w,algorithm ="default")
bcd<-summary(abc)






e0[i]<-bcd$coef[1]
emax[i]<-bcd$coef[2]
e50[i]<-bcd$coef[3]


tryCatch(1, finally = print("failed"))

}  

1 个答案:

答案 0 :(得分:0)

将您的代码括起来如下:

try( {
 # put your code here
 # ...

},silent=FALSE)