If error, next iteration in a for loop in R -
i'm looking simple way move on next iteration in loop in r if operation inside loop errors.
i've recreated 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 following calc values.
[1] 2 [1] 4
however once change vector in include 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 loop doesn't work. hoping same calc values above vector excluding non-numeric value in i.
i tried using trycatch following:
for(i in c(1, "a", 3)) { calc <- trycatch({i+1}, error = function(e) {next}) print(calc) }
however, following error:
error in value[[3l]](cond) : no loop break/next, jumping top level
could please me understand how achieve using loop in r?
as dason noted, atomic vector not best way of storing mixed data types. lists that. consider following:
l = list(1, "sunflower", 3) for(i in seq_along(l)) { this.e = l[[i]] test <- try(this.e + 1, silent=true) calc <- if(class(test) %in% 'try-error') {next} else {this.e + 1} print(calc) } [1] 2 [1] 4
in other words, former loop "worked". always failed , went next iteration.
Comments
Post a Comment