On Jul 12, 2010, at 6:18 PM, Josh B wrote:

Hi R sages,

Here is my latest problem. Consider the following toy example:

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)

I want to fit a logistic regression of y1 on x1 and x2. Then I want to run a logistic regression of y2 on x1 and x2. Then I want to run a logistic regression of y3 on x1 and x2. In reality I have many more Y columns than simply "y1," "y2," and "y3," so I must design a loop. Notice that y2 is invariant and thus it will fail. In reality, some y columns will fail for much more subtle reasons. Simply screening my data to eliminate invariant columns will not eliminate the
problem.

What I want to do is output a piece of the results from each run of the loop to a matrix. I want the to try each of my y columns, and not give up and stop running simply because a particular y column is bad. I want it to give me "NA" or something similar in my results matrix for the bad y columns, but I want it
to keep going give me good data for the good y columns.

For instance:
results <- matrix(nrow = 1, ncol = 3)
colnames(results) <- c("y1", "y2", "y3")

for (i in 1:2) {
mod.poly3 <- lrm(x[,i] ~ pol(x1, 3) + pol(x2, 3), data=x)
results[1,i] <- anova(mod.poly3)[1,3]
}

If I run this code, it gives up when fitting y2 because the y2 is bad. It
doesn't even try to fit y3. Here's what my console shows:

results
           y1 y2 y3
[1,] 0.6976063 NA NA

As you can see, it gave up before fitting y3, which would have worked.

How do I force my code to keep going through the loop, despite the rotten apples
it encounters along the way?

?try

http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-capture-or-ignore-errors-in-a-long-simulation_003f

(Doesn't only apply to simulations.)

Exact code that gets the job done is what I am
interested in. I am a post-doc -- I am not taking any classes. I promise this is
not a homework assignment!

--

David Winsemius, MD
West Hartford, CT

______________________________________________
R-help@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.

Reply via email to