Zoë Clark
Zoë Clark

Reputation: 1364

Saving workspace (in a particular frame) for post-mortem debugging in R

While debug some R code, I'd like to save the workspace (i.e. all present objects) in some particular frame so that I can utilize those objects outside of the the debugging browser. Following the example given in this answer:

x <- 1:5
y <- x + rnorm(length(x),0,1)
f <- function(x,y) {
  y <- c(y,1)
  lm(y~x)
}

Setting options(error = recover) and running f(x,y) allows us to pick which frame to enter. Here I'll pick 2 and check my workspace with ls() like so:

Browse[1]> ls()
 [1] "cl" "contrasts" "data" "formula" "m" "method" "mf" "model" "na.action" "offset" "qr"         
[12] "ret.x" "ret.y" "singular.ok" "subset" "weights" "x" "y"

I'd like to be able to save all of these objects to use them later. Using save.image() in the browser, or inserting it into the relevant function, saves the environment f(x,y) was originally called from. I can use dump.frames() and call debugger() on the resulting dump.frames classed object, but I still have to work interactively from within the debugging browser. All I really want is an .RData file containing the 18 above listed objects.

The point of all this is to reproduce certain errors within an R Markdown document. If anyone has an idea for that particular application it would be appreciated.

Upvotes: 6

Views: 1405

Answers (1)

IRTFM
IRTFM

Reputation: 263362

save(list=ls(), file="mylocals.Rda")

The hurdle I had to get over to realize this was the way forward was the name of that argument in save. Why did the authors use the argument name, "list", when it was a character vector (and not a list)? Same whine applies to the rm function argument names.

Upvotes: 9

Related Questions