[R] Question regarding if statement in while loop
Carl Witthoft
carl at witthoft.com
Sat Dec 26 22:56:00 CET 2009
Sounds like what you want is either try() or trycatch() -- check out
the documentation. Basically, putting your eblest() function inside a
try() call allows you to return an error message if eblest crashes
without crashing your main loop.
BTW, for debugging purposes, I'd recommend creating a simple loop with
an input some of whose values are guaranteed to cause a problem. For
example:
xin<-c(1,2,3,4,-5,6)
i<-1
while(i<=length(xin)){
sqrt(xin[i])
}
Carl
<original message follows>
I'm running R version 2.9.2 on a PC.
I'm having a problem with a loop, and have tried using an if statement
within to fix it, but to no avail.
Any advice would be appreciated.
Here is my code:
eblest <- function(i,dir, sterr, weight, aux) { n <- nrow(dir)
Y <- as.matrix(dir[,i], ncol=1)
sigma2ei <- as.matrix(sterr[,i]^2, ncol=1)
w <- as.matrix((weight[,3])*(sigma2ei), ncol=1)
X <- as.matrix(subset(aux, select=c(3,5:7,9:10,13)))
a <<- EBLUP.area(Y,cbind(w,1),sigma2ei,n) #The EBLUP.area
function is a function already in R.
}
# It gives a bunch of output, some of what I need.
#THIS IS THE LOOP I'M HAVING A PROBLEM WITH: results <-
data.frame(length=nrow(dir5)) i <- 3
while (i <=some number) {
eblest(i, dir5, sterr5, weight5, aux5)
out <<- cbind(i, a$EBLUP, a$mse)
results <- cbind(results, out)
i <- i+1
}
I have tried running the eblest function for a specific set of input (i,
dir5, etc as in the function) This function runs ok. However, sometimes
eblest does not create the expected output, sometimes due to the
solution being singular or other reasons. I'm not so concerned about
that at this point - it's a function of the data.
My problem is that, as you can see, after eblest runs, the "out" pieces
of information are bound together in the results matrix. When the eblest
does not run correctly, the loop stops. For example, when i=3 and i=4,
eblest runs ok, and I get a maxtrix with the following columns:
i EBLUP se.EBLUP i EBLUP se.EBLUP
3 x y 4 a bh
...but when it loops back around to start i=5, I get an error because
the solution is singular. But I don't want the loop to stop (I have ~100
of these i's for which I need to execute this function.
So I would like to set an if condition that will cause the loop to step
ahead (in this case, to 6), and continue looping...Something like "if
exists("out")=FALSE next, else..." However, when I tried that, the
results matrix was empty created at all.
In case it helps, "out" has a "numeric" mode, and is a "matrix"...
I've written these functions and loops using online help and examples
I've found on websites, but clearly I'm missing something.
Thanks for any help you can give!!
More information about the R-help
mailing list