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")})
}
R tryCatch skips error in for loop but error statement is not executed
This because the tryCatch
should wrap the cor.test()
function and not the append()
one. Also, you may use sapply()
instead of a for
loop here.
Generate some data
x <- data.frame(A=sample(1:100, size = 20),
B=sample(1:100, size = 20),
C=sample(1:100, size = 20),
D=sample(1:100, size = 20))
y <- data.frame(A=sample(1:100, size = 20),
B=sample(1:100, size = 20),
C=sample(1:100, size = 20),
D=NA)
And now the code
result <- sapply(2:ncol(x), (function(i){
tryCatch({cor.test(x[,i], y[,i], na.action = "na.omit", method = "spearman")$p.value},
error = function(e) NA)
}))
result
[1] 0.7238886 0.2668126 NA
Now, the result
vector includes a NA
corresponding to the correlation test between a numeric vector and a series of NA
.
R: For loop skip if error / tryCatch
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.
Related Topics
Why Would R Use the "L" Suffix to Denote an Integer
How to Make Geom_Text Plot Within the Canvas's Bounds
Tidyverse Pivot_Longer Several Sets of Columns, But Avoid Intermediate Mutate_Wider Steps
How to One Hot Encode Several Categorical Variables in R
How to Add Legend to Ggplot Manually? - R
Ggplot2: Facet_Wrap Strip Color Based on Variable in Data Set
Generate Random Numbers with Fixed Mean and Sd
Remove Everything After Space in String
In R Markdown in Rstudio, How to Prevent the Source Code from Running Off a PDF Page
Why Do Some Unicode Characters Display in Matrices, But Not Data Frames in R
Is There a More Elegant Way to Convert Two-Digit Years to Four-Digit Years with Lubridate
Adding Space Between Bars in Ggplot2
Why Does R Use Partial Matching
Code to Import Data from a Stack Overflow Query into R
How to Make Tibbles Display Significant Digits
How to Add Table of Contents in Rmarkdown