[R] Problem with error handling inside a function

Gabor Grothendieck ggrothendieck at gmail.com
Sat Oct 25 16:18:08 CEST 2008


Try this:

evaluate.all <- function(response, DF = iris) {

	DF <- cbind(response = DF[[response]], DF)

	L <- list(

	# some linear models:
		B1 = try(lm(response ~ Sepal.Length, DF)),
		L2 = try(lm(response ~ Sepal.Width, DF)),

		# some nonlinear models:
		M1 = try(nls(response ~ a*Sepal.Length/(b+Sepal.Length),
				start=list(a=1,b=1), DF)),
		E1 = try(nls(response ~ a+b*exp(c*Sepal.Length),
				start=list(a=1,b=1,c=1), DF))
	)

	sapply(Filter(function(x) !inherits(x, "try-error"), L), extractAIC)
}
evaluate.all("Petal.Width", iris)

On Sat, Oct 25, 2008 at 9:48 AM, Dr. Christoph Scherber
<Christoph.Scherber at agr.uni-goettingen.de> wrote:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list