[R] Problem with error handling inside a function
Dr. Christoph Scherber
Christoph.Scherber at agr.uni-goettingen.de
Sat Oct 25 15:48:36 CEST 2008
Dear R users,
I have written a function that runs several statistical models and extracts
the AIC values from them.
As a (nonsense) example, I use the iris dataset:
#############
data(iris)
attach(iris)
evaluate.all=function(response,...){
response=get(response) #retrieves the response variable
# some linear models:
B1=lm(response~Sepal.Length,iris)
L2=lm(response~Sepal.Width,iris)
# some nonlinear models:
M1=nls(response~a*Sepal.Length/(b+Sepal.Length),start=list(a=1,b=1),iris)
E1=nls(response~a+b*exp(c*Sepal.Length),start=list(a=1,b=1,c=1),iris)
#[... and so on]
#now paste the names of the models together
mm=c("B1","L2","M1","E1")
# and extract the AICs for those models that exist in the .GlobalEnv
extracted.AICs=
sapply(mm[which(sapply(mm,function(x)exists(x,-1))==T)],function(x){x=get(x);extractAIC(x)})
# finally, print those values
print(extracted.AICs)
}
evaluate.all("Petal.Width")
#############
Now the problem is that the function stops because the nonlinear models
produce error messages.
I have tried "try()", options() and other things already, but without
success.
How can I make the code run, so that the nonlinear models are "skipped"
and the extracted.AICs are still printed?
Many thanks for any help!
All the best
Christoph
--
Christoph Scherber
Agroecology, Univ. Goettingen
37073 Goettingen
Germany
More information about the R-help
mailing list