Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to have R script continue after receiving error messages instead of halting execution?

Tags:

r

statistics

I am currently running ANOVA for a project at school that has a large number of possible runs (1400 or so) but some of them aren't able to run ANOVA in R. I wrote a script to run all the ANOVA's, but some of them will not run and the Rout file gives me Error in contrasts<-(*tmp*, value = "contr.treatment") : contrasts can be applied only to factors with 2 or more levels Calls: aov ... model.matrix -> model.matrix.default -> contrasts<- Execution halted

Is there any way to write the script that will make R continue the script despite the error?

My entire script, other then the file loading, attaching, creating a sink, library loading, etc is...

ss107927468.model<-aov(Race.5~ss107927468, data=snp1)
summary(ss107927468.model)

Any help would be appreciated.

like image 983
James Anderson Avatar asked Dec 05 '10 14:12

James Anderson


2 Answers

See the function try() and it's help page (?try). You wrap your R expression in a try() call and if it succeeds, the resulting object contains, in this case, the fitted model. If it fails, then an object with class "try-error" is returned. This allows you to easily check which models worked and which didn't.

You can do the testing to decide whether to print out the summary for the model or just a failure message, e.g.:

ss107927468.model <- try(aov(Race.5~ss107927468, data=snp1))
if(isTRUE(all.equal(class(ss107927468.model), "try-error"))) {
    writeLines("Model failed")
} else {
    summary(ss107927468.model)
}
like image 52
Gavin Simpson Avatar answered Oct 14 '22 18:10

Gavin Simpson


I use failwith in the plyr package. You can use this in combination with llply and wrap your function around it.

like image 32
Maiasaura Avatar answered Oct 14 '22 19:10

Maiasaura