From hadley at rice.edu  Tue May 10 16:35:03 2011
From: hadley at rice.edu (Hadley Wickham)
Date: Tue, 10 May 2011 09:35:03 -0500
Subject: [Rd] Debugging warnings
Message-ID: <BANLkTimn7nv3VwUGf-fV+0miCtGz3y2D3Q@mail.gmail.com>

Hi all,

One thing that's currently a little tricky in R is debugging warnings.
 One solution is to turn them into errors and then use the usual error
tracking mechanisms (e.g. options(error = recover)).  But it should be
possible to use withCallingHandlers to provide more flexibility.  The
function below works, but I'm wondering if there's a more elegant way
to figure out the correct frame to evaluate the action in - I'm
currently counting back one from where warning was called.

on_warning <- function(action, code) {
  q_action <- substitute(action)

  withCallingHandlers(code, warning = function(c) {
    for(i in seq_len(sys.nframe())) {
      f <- as.character(sys.call(i)[[1]])
      if (f == "warning") break;
    }

    eval(q_action, sys.frame(i - 1))
  })
}

x <- 1
f <- function() {
  x <- 2
  g()
}
g <- function() {
  x <- 3
  warning("Leaving g")
}
on_warning(browser(), f())
on_warning(print(ls()), f())

Thanks,

Hadley


-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



[Rd] Debugging warnings
Hadley Wickham