[R] question about TryCatch and lapply

jim holtman jholtman at gmail.com
Fri May 25 21:23:22 CEST 2012


Please show us the 'lapply' statement you are using.  Here is a simple
case of catching an error in an lapply and continuing:

> lapply(c(1,2,-3, 4), function(x){
+     a <- try(stopifnot(x > 0))  # force an error
+     if (inherits(a, 'try-error')) return(NULL)
+     x
+ })
Error : x > 0 is not TRUE
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
NULL

[[4]]
[1] 4

>


On Fri, May 25, 2012 at 2:51 PM, John Kerpel <john.kerpel at gmail.com> wrote:
> Folks:
>
> I've replaced an outer for-loop with lapply and it works great.  But, I
> can't seem to do the following type of exception handling:
>
> tryCatch(dlmMLE(x)$value==Inf,error = function(e) NULL)
>
> which basically says if the likelihood is Inf, throw an error.  But what I
> want it to do is just go to the next index in the list.  When I was using a
> for-loop I used:
>
> if(tryCatch(dlmMLE(x)$value==Inf,error = function(e) 1)==1) {next} else
> .... which worked fine.
>
> Is there a way to do the same thing in lapply?
>
> Thanks for your time. (I've checked Gmane for this type of problem and I
> wasn't sure if this problem was answered or not...)
>
> John
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list