user4918087
user4918087

Reputation: 421

R: For loop skip if error / tryCatch

I have a dataframe of 1000 rows. The code I want to loop through is very simple - I just want to make all the values in column 4 uppercase. I want it such that if there is an error in any of the rows, I want it to skip that row and continue to the rest of the rows.

I've written this code:

for(i in 1:1000)
{
  tryCatch(toupper(Total_Data_2[i,4]), error = function(e) next)
}

However, I get the error: Error in value[[3L]](cond) : no loop for break/next, jumping to top level

Can someone help me with this? I could do a tryCatch or some sort of if iserror.

Thanks in advance!!

Upvotes: 2

Views: 6537

Answers (1)

BrodieG
BrodieG

Reputation: 52637

While I don't think this is necessarily the best solution, it does answer your question directly (simplified for reproducibility):

for(i in 1:10) {
  res <- try(if(i %% 2) stop("argh"))
  if(inherits(res, "try-error")) next
  cat(i, "\n")
}

Just using try instead of tryCatch b/c it's a bit simpler and tryCatch functionality is not needed. Really for your purposes you could:

for(i in 1:10) try(my_val[i] <- my_fun(my_val[i]))

since you don't need to do anything else. If it fails, the loop will just keep going merrily.

All this said, I have to say I am a bit confused by your error and the inability to do this in a vectorized manner.

Upvotes: 5

Related Questions