Patrick McKann
2010-Jul-20 13:44 UTC
[R] Nesting functions in loops that result in error messages breaking the loop
Hello all, I am trying to write a program in R in which I call a function multiple times within a loop. The problem is that sometimes the function breaks down while calling another function, and produces an error message that breaks my loop and the program stops. I would like to keep the loop running when this function breaks down, and just move on to the next iteration in the loop. Is there any way to buffer the output of a function within the loop, so that I can note that the function produced an error message, without the error message breaking the loop and stopping my program? Let me know if this question does not make sense. Thanks, Patrick [[alternative HTML version deleted]]
David Winsemius
2010-Jul-20 13:55 UTC
[R] Nesting functions in loops that result in error messages breaking the loop
On Jul 20, 2010, at 9:44 AM, Patrick McKann wrote:> Hello all, > > I am trying to write a program in R in which I call a function > multiple > times within a loop. The problem is that sometimes the function > breaks down > while calling another function, and produces an error message that > breaks my > loop and the program stops. I would like to keep the loop running > when this > function breaks down, and just move on to the next iteration in the > loop. > Is there any way to buffer the output of a function within the loop, > so that > I can note that the function produced an error message, without the > error > message breaking the loop and stopping my program? Let me know if > this > question does not make sense.?try This is a worked example that Josh Barnett posted a couple of days ago after some (lengthy) coaching: x <- read.table(textConnection("y1 y2 y3 x1 x2 indv.1 bagels donuts bagels 4 6 indv.2 donuts donuts donuts 5 1 indv.3 donuts donuts donuts 1 10 indv.4 donuts donuts donuts 10 9 indv.5 bagels donuts bagels 0 2 indv.6 bagels donuts bagels 2 9 indv.7 bagels donuts bagels 8 5 indv.8 bagels donuts bagels 4 1 indv.9 donuts donuts donuts 3 3 indv.10 bagels donuts bagels 5 9 indv.11 bagels donuts bagels 9 10 indv.12 bagels donuts bagels 3 1 indv.13 donuts donuts donuts 7 10 indv.14 bagels donuts bagels 2 10 indv.15 bagels donuts bagels 9 6"), header = TRUE) closeAllConnections() results <- matrix(nrow = 1, ncol = 3) colnames(results) <- c("y1", "y2", "y3") require(rms) # or Design for (i in 1:3) { mod.poly3 <- try(lrm(x[,i] ~ pol(x1, 3) + pol(x2, 3), data=x), silent=TRUE) if(class(mod.poly3)[1] != 'try-error') {results[1,i] <- anova(mod.poly3)[1,3]} David Winsemius, MD West Hartford, CT
Possibly Parallel Threads
- Continuing on with a loop when there's a failure
- Splitting a data frame into several completely separate data frames
- Extracting P-values from the lrm function in the rms library
- Indexing a matrix within loops
- as.object: function doesn't exist but I wish it did