purple1437
purple1437

Reputation: 313

If there's an error in an R loop, return NA or zero and continue with the loop

I'm building an R Shiny App and it gets very cumbersome when errors are introduced. I have a dataframe and I am looping through the rows using an NLS function and returning the EC50 value. The EC50 are then added to the original dataframe to display. Not every observation will fit so it returns an error and the app breaks.

What I would like is a way to return a NA or 0 when there are errors and for the loop to move on to other observations. A simple example of the code would be

df <- data.frame(x = c(1,2,3), y = rep('hi',3))

addition <- function(a,b){
  result <- a+b
  return(result)
}

df$z <- 1
for (i in 1:length(df$x)){
  df$z[i] <- addition(df$x[i], df[i,i])
}

The results I would like is as below:

x y z
1 hi 2
2 hi NA
3 hi 6

This is just a sample. What I'm doing is more complicated but I want to return NA/0 with any types of error, and since it's user uploaded files, I wouldn't be able to know which index the error is going to be in.

Upvotes: 0

Views: 1842

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174468

You could use tryCatch here. When an error is caught, it can simply return an NA; otherwise it returns the result of the calculation:

df <- data.frame(x = c(1,2,3), y = rep('hi',3))
df$z <- 1

for (i in 1:length(df$x)){
   df$z[i] <- tryCatch(
    addition(df$x[i], df[i,i]), 
    error = function(e) return(NA)
    )
}

df
#>   x  y  z
#> 1 1 hi  2
#> 2 2 hi NA
#> 3 3 hi  4

Created on 2022-08-10 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions