I'm looking for a simple way to move on to the next iteration in a for loop in R if the operation inside the for loop errors.
I've recreated a simple case below:
for(i in c(1, 3)) {
test <- try(i+1, silent=TRUE)
calc <- if(class(test) %in% 'try-error') {next} else {i+1}
print(calc)
}
This correctly gives me the following calc values.
[1] 2
[1] 4
However once I change the vector in i to include a non-numeric value:
for(i in c(1, "a", 3)) {
test <- try(i+1, silent=TRUE)
calc <- if(class(test) %in% 'try-error') {next} else {i+1}
print(calc)
}
This for loop doesn't work. I was hoping for the same calc values as above with the vector excluding the non-numeric value in i.
I tried using tryCatch as the following:
for(i in c(1, "a", 3)) {
calc <- tryCatch({i+1}, error = function(e) {next})
print(calc)
}
However, I get the following error:
Error in value[[3L]](cond) : no loop for break/next, jumping to top level
Could someone please help me understand how I could achieve this using a for loop in R?
c(1, "a", 3)actually is. I think you believe that only the middle element is character but that is incorrect.as.numericon the input vector will make the characters into NA. Play around with itas.numeric(c(1, "k", "3")) + 1