Reputation: 11686
I often have the situation like this:
result <- lapply(1:length(mylist), function(x){
doSomething(x)
})
However, if it fails, I have no idea which element in the list failed on doSomething().
So then I end up recoding it as a for loop:
for(i in 1: length(mylist)){
doSomething(mylist[[i]])
}
I can then see the last value of i
and what happened. There must be a better way to do this right?? Thanks!
Upvotes: 1
Views: 540
Reputation: 46856
Notice how the error includes 5L
> lapply(1:10, function(i) if (i == 5) stop("oops"))
Error in FUN(1:10[[5L]], ...) : oops
indicating that the 5th iteration failed.
Upvotes: 3
Reputation: 49640
One simple option is to run the code:
options( error=recover )
before running lapply
(see ?recover
for details).
Then when/if an error occurs you will instantly be put into the recover mode that will let you examine which function you are in, what arguments were passed to that function, etc. so you can see which step you are on and what the possible reason for the error is.
You can also use try
or tryCatch
as mentioned in the comments to either skip elements that produce an error or print out information on where they occur.
Upvotes: 2