Free data science video lecture: debugging in R
Win-Vector Blog 2016-04-12
We are pleased to release a new free data science video lecture: Debugging R code using R, RStudio and wrapper functions. In this 8 minute video we demonstrate the incredible power of R using wrapper functions to catch errors for later reproduction and debugging. If you haven’t tried these techniques this will really improve your debugging game.
All code and examples can be found here and in WVPlots.
For those that don’t want to watch the video or follow links, below is the (non-printing) version of the wrapper.
#' Capture arguments of exception throwing plot for later debugging.#'#' Run fn, save arguments on failure.#'#' @param saveFile path to save RDS to.#' @param fn function to call#' @param ... arguments for fn#' @return fn(...) normally, but if f(...) throws an exception,#' save to saveFile RDS of list r such that do.call(r$fn,r$args) #' repeats the call to fn with args.#'DebugFn <- function(saveFile,fn,...) { args <- list(...) tryCatch({ res = do.call(fn,args) res }, error = function(e) { saveRDS(object=list(fn=fn,args=args),file=saveFile) stop(paste0("Wrote '",saveFile,"' on catching '",as.character(e),"'")) })}
And how to use it.
> f <- function(a,b) { a[[b]] }> f(0,0)Error in a[[b]] : attempt to select less than one element> DebugFn('example.RDS','f',0,0)Error in value[[3L]](cond) : Wrote 'example.RDS' on catching 'Error in a[[b]]: attempt to select less than one element' > p <- readRDS('example.RDS')> print(p)$fn[1] "f"$args$args[[1]][1] 0$args[[2]][1] 0> do.call(p$fn,p$args)Error in a[[b]] : attempt to select less than one element>
If you are using RStudio you may need to toggle the RStudo->Debug->”On Error” message settings to “Message Only” on the capture run (see below).
However, for context I strongly recommend watching the short video and checking the included resources. Also, please check here and here for more ideas.