# [R] testing for error

From: Jonathan Williams <jonathan.williams_at_pharmacology.oxford.ac.uk>
Date: Mon 09 Oct 2006 - 16:12:27 GMT

I want to test if a procedure within a loop has produced an error or not. If the procedure has produced an error, then I want to ignore its result. If it has not produced an error, then I want to use the result. The problem In order to run the loop without crashing if the procedure produces an error,
I place the routine inside a try() statement.

So, suppose I am trying to find the predicted values for a regression in a loop
If the procedure now produces an error, I can detect it with:-

if grep('Error', result)<1 #and so choose not use the result

but if the procedure does not produce an error, then "if grep('Error', result)<1"
now produces the result logical(0) and the loop then fails with the message

set.seed(1)
cumulator=rep(0,100)
for (i in 1:100){

```y1=rnorm(100)
x0=rbinom(100,1,0.02)
x1=rbinom(100,1,0.5)
x2=rbinom(100,1,0.5)
```

x1[x0]=NA
dat=data.frame(y1,x1)
result=try(lm(y1~x1, na.action=na.fail, data=dat),T); print(result) x1=x2; dat2=data.frame(x1)
if (grep('Error',result)<1) cumulator=cumulator+predict(result,x2) }

The above runs and rejects the 'result' until i=6, when lm runs and grep('Error', result) gives:-

Error in if (grep("Error", pred1) < 1) for (i in labels(pred1)) votes[rownames(votes) == :

argument is of length zero

but, predict(result,dat2) runs fine.

So, how do I trap or use the 'logical(0)' state of grep('Error', result) to obtain
and accumulate my result?