Skipping error in for-loop

前端 未结 3 1164
闹比i
闹比i 2020-11-27 10:39

I am doing a for loop for generating 180 graphs for my 6000 X 180 matrix (1 graph per column), some of the data don\'t fit my criteria and i get the error:



        
相关标签:
3条回答
  • 2020-11-27 10:57

    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")})
    }
    
    0 讨论(0)
  • 2020-11-27 11:09

    Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

    0 讨论(0)
  • 2020-11-27 11:12

    Here's a simple way

    for (i in 1:10) {
    
      skip_to_next <- FALSE
    
      # Note that print(b) fails since b doesn't exist
    
      tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
    
      if(skip_to_next) { next }     
    }
    
    

    Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

    0 讨论(0)
提交回复
热议问题