1

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.

Li_Q
  • 123
  • 5
  • For error handling, try using e.g. `tryCatch`, see [here](http://stackoverflow.com/questions/22021775/i-dont-understand-how-to-catch-an-error/22021936#22021936) or [here](http://stackoverflow.com/questions/12193779/how-to-write-trycatch-in-r) – gagolews Jun 12 '14 at 16:35

1 Answers1

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