2

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!!

5
  • What errors are you expecting? I would just do Total_Data_2[, 4] = toupper(Total_Data_2[, 4]), no need for a loop. Commented Jun 5, 2015 at 16:24
  • I have some special characters in some of the rows. That causes errors. Commented Jun 5, 2015 at 16:25
  • What are those special characters? Commented Jun 5, 2015 at 16:28
  • Even if base R doesn't handle special characters well, stringi probably does. Try Total_Data_2[, 4] = stringi::stri_trans_toupper(Total_Data_2[, 4]) Commented Jun 5, 2015 at 16:29
  • I'm not exactly sure, but I'm thinking it's because of foreign language conversion. Maybe it's not exactly a special character, but in one of my lines, I have a question mark inside a diamond. (And I have several of these occurences) Commented Jun 5, 2015 at 16:30

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.