Is there a way to `source()` and continue after an error?

前端 未结 3 723
南方客
南方客 2020-11-28 05:45

I have a large R script of, say, 142 small sections. If one section fails with an error I\'d like the script to continue rather than halt. The sections don\'t necessarily de

3条回答
  •  悲哀的现实
    2020-11-28 06:03

    this is clunky and uses nobody's friend eval(parse( but might be somewhat helpful.. josh's answer is much cleaner.

    # assign the filepath
    fn <- "c:/path/to your/script.R"
    
    # read in the whole script
    z <- readLines( fn )
    
    # set a starting j counter
    j <- 1
    
    # loop through each line in your script..
    for ( i in seq(length(z)) ) {
    
        # catch errors
        err <- try( eval( parse( text = z[j:i] ) ) , silent = TRUE )
    
        # if it's not an error, move your j counter up to one past i
        if ( class( err ) != 'try-error' ) j <- i + 1 else
    
        # otherwise, if the error isn't an "end of input" error,
        # then it's an actual error and needs to be just plain skipped.
        if ( !grepl( 'unexpected end of input' , err ) ) j <- i + 1
    
        # otherwise it's an "end of line" error, which just means j alone.
    }
    

提交回复
热议问题