[R] testing for error
Henrik Bengtsson
hb at stat.berkeley.edu
Mon Oct 9 18:37:08 CEST 2006
tryCatch() is doing exactly what you need. I consider tryCatch() an
updated and more flexible version of try() making the latter history.
/H
On 10/9/06, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> See:
>
> http://www.mail-archive.com/r-help@stat.math.ethz.ch/msg09925.html
>
> On 10/9/06, Jonathan Williams
> <jonathan.williams at pharmacology.oxford.ac.uk> wrote:
> > Dear R Helpers,
> >
> > 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?
> >
> > Thanks in advance for your help
> >
> > Jonathan Williams
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch 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.
> >
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>
More information about the R-help
mailing list