Skip an error in a loop && debug in R

When writing R code, it is important to know how to debug.

    1. In for loop, once bug occurred, to to skip the error and continue loop:

count <- 0
repeat {
if (count == 100) break
count <- count + 1
x <- matrix(sample(0:2, 4, replace = T), 2, 2)
x.inv <- try(solve(x), silent=TRUE)
if ('try-error' %in% class(x.inv)) next
else inverses[[count]] <- x.inv
}

2. To test an R function, simply use debug()

when run debug() command

  • n(next): to run the next command line,and pause after next line, which gives us a way to run code line by line.
  • c(continue): to run several lines. If present in a loop, this command will run the entire loop; while in stays in a function but loop, then R will run over the function.
  • where: output present location, show the array of functions till present code line.
  • Q: exit browser.

3. Set break point setBreakpoint()

require(utils)

setBreakpoint(filename,linenumber)

  This will set break point at line number linenumber in filename. Notice this should set in a function.  This command can be used while debug() which runs the code till break point.

cancel break point :  untrace(fun)

 

Leave a Reply

Your email address will not be published. Required fields are marked *