R "For Loop" Error Messages {}

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
print(i)
if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
tryCatch({
print(i)
if (i==7) stop("Urgh, the iphone is in the blender !")
}, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
tryCatch({
print(i)
if (i==7) stop("Urgh, the iphone is in the blender !")
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender !
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
tryCatch({
mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
pdf(file=mypath)
mytitle = paste("anything")
myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
dev.off()
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

Error in for loop in r

Count your parentheses (or use a good editor that helps with matching).

You have 3 openening parens, then only 2 closing before the 1st brace ({), you need one more closing paren before the brace to match the one for the for condition.

Also, you can do this much simpler with the ifelse function and not need the loop.

How can you continue the for loop in R even after an error?

Maybe something like this?

library(rvest)

house_link <- "https://lalafo.kg/bishkek/ads/104-seria-2-komnaty-47-kv-m-s-mebelu-kondicioner-zivotnye-ne-prozivali-id-95221626"
house_features = data.frame()

for(x in 1:3) { # seq_along(house_link) <- if you have more than 1 link this is the correct method

cat('Link', x)

start_time <- Sys.time()
if (x %% 200 == 0) {
Sys.sleep(5)
print("pausing ...")}

page_data <- tryCatch({
page_data = read_html(house_link[x])
message("Executed.")
}, error = function(e){
message('\nCaught an error!')
return(NA) # here a return variable for testing is returned in the error condition - notice that this has to be initiated with the return function
}, finally = {cat('Continuing with', x+1,'\n')}) #; next()}) <- disabled next()

## This part is handled by finally next()
############################
if(is.na(page_data)){ #
cat('this is a test\n') #
next() #
} #
############################

else{ # else is not strictly necessary but the point may be easier to contextualised like this
pricing = page_data %>% html_nodes(".css-13sm4s4") %>%
html_element("span") %>% html_text()
house_features = rbind(house_features, data.frame(pricing, stringsAsFactors = FALSE))
}
}

Link 1
Caught an error!
Continuing with 2
this is a test

Link 2
Caught an error!
Continuing with 3
this is a test

Link 3
Caught an error!
Continuing with 4
this is a test

How to skip only a specific type of error in for-loop in R?

You could try this:

test <- function(x) {
tryCatch(x,
error = function(e) {if(conditionMessage(e) == "It's an error") {print("no problem")
} else {
stop("It's another error")}
})
}

> test(stop("It's an error"))
[1] "no problem"

> test(stop("Mayday mayday"))
Error in value[[3L]](cond) : It's another error

conditionMessage captures the error message, so you can evaluate it and act accordingly.

For it to do nothing just "do nothing" {} when the condition is true.

R: Can't use paste0 function within a for loop

We don't need a loop here. This can be done with sprintf directly on the vector

sprintf('%03d', a)

In the loop, there was no assignment to the original vector element and no print, thus it didn't return anything

a <- as.character(a)
for(i in 1:93){
if(nchar(a[i]) < 3){
a[i] <- paste0("0", a[i])
}
}

continue not in loop' error while trying to add an error handling mechanism

It seems that what you are actually wanting to do is keep looping until no exception is raised.

In general, you can do this by having an infinite loop that you break from in the event of a successful completion.

Either:

while True:
try:
# do stuff
except requests.ConnectionError:
# handle error
continue
except requests.exceptions.ReadTimeout:
# handle error
continue
break

Or:

while True:
try:
# do stuff
except requests.ConnectionError:
# handle error
except requests.exceptions.ReadTimeout:
# handle error
else:
break

However, in this case, the "do stuff" seems to always end by reaching a return statement, so the break is not required, and the following reduced version would suffice:

while True:
try:
# do stuff
return some_value
except requests.ConnectionError:
# handle error
except requests.exceptions.ReadTimeout:
# handle error

(The single return shown here may refer to alternative control flows, all of which lead to a return, as in your case.)



Related Topics



Leave a reply



Submit