I am using apply function to execute a function for each row of my data. I found if one row of the data triggers an error, I will not get result back. I wonder if there is a way to let the apply function give an error or NA for that problematic row but still run for the other rows.
Asked
Active
Viewed 1,447 times
1 Answers
2
You need to wrap your applied function in a tryCatch
that will return NA if it fails.
Stop if x less than zero:
> foo = function(x){if(x<0)stop("Zerrored");sqrt(x)}
Try it
> apply(matrix(0:5),1,foo)
[1] 0.000000 1.000000 1.414214 1.732051 2.000000 2.236068
> apply(matrix(-2:5),1,foo)
Error in FUN(newX[, i], ...) : Zerrored
Darn. Wrap in a tryCatch
:
> tryfoo=function(x){tryCatch(foo(x),error=function(e){NA})}
> apply(matrix(-2:5),1,tryfoo)
[1] NA NA 0.000000 1.000000 1.414214 1.732051 2.000000 2.236068
Works!
You might want to raise a warning if the function errors:
> tryfoo=function(x){tryCatch(foo(x),error=function(e){warning("Zerrored");NA})}
> apply(matrix(-2:5),1,tryfoo)
[1] NA NA 0.000000 1.000000 1.414214 1.732051 2.000000 2.236068
Warning messages:
1: In value[[3L]](cond) : Zerrored
2: In value[[3L]](cond) : Zerrored
Again it doesn't stop the apply.

Spacedman
- 92,590
- 12
- 140
- 224
-
I have more than one arguments to be passed to the function. Would you please tell me how to pass multiple arguments in the tryCatch function. Thank you! – Li_Q Jun 12 '14 at 17:03
-
If your function is `foo(a,b,c)` then `tryfoo` is a `function(a,b,c)` and you pass those through to your `foo` function inside. – Spacedman Jun 12 '14 at 17:05