9

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    Some new answers today. Either http://stackoverflow.com/a/14612524/403310 (looped `try(eval(...))` on each expression in the result of `parse("file.R")`, or http://stackoverflow.com/a/14613363/403310 (the `evaluate` package). – Matt Dowle Jan 30 '13 at 21:59

2 Answers2

7

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)
}
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • Quick update: it seems, as of 2013-02-12, that the class of a `try` object that failed is `try-error`. – Fr. Feb 12 '13 at 19:28
  • @Fr. Thanks for that. I don't think this has changed and so perhaps I was confusing this with `tryCatch()`? Anyway, thanks for pointing out the issue. – Gavin Simpson Feb 12 '13 at 20:16
  • `try()` is presented more or less as a simpler wrapper for `tryCatch`, so it should be the same object. But it's actually not: `x <- try(stop(e))` returns an object of class `try-error`, and `x <- tryCatch(stop(e), error = function(e) e)` returns an object of class `c("simpleError", "error", "condition"). I'm a bit lost in all of that, to speak frankly :) – Fr. Feb 12 '13 at 22:29
3

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

Maiasaura
  • 32,226
  • 27
  • 104
  • 108
  • Yep - this is how I usually approach these problems as well. The [plyr tutorial](http://had.co.nz/plyr/plyr-intro-090510.pdf) has a couple nice example using `faithwith`. – Chase Dec 05 '10 at 22:25