Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
Zoë Clark Avatar asked Aug 02 '13 17:08

Zoë Clark


People also ask

What does saving workspace do in R?

Saving your workspace creates an image of your current variables and functions, and saves them to a file called ”. RData”. When you re-open R from that working directory, the workspace will be loaded, and all these things will be available to you again.

How do I run a debug in RStudio?

You can do this in RStudio by clicking to the left of the line number in the editor, or by pressing Shift+F9 with your cursor on the desired line. We call this an “editor breakpoint”. Editor breakpoints take effect immediately and don't require you to change your code (unlike browser() breakpoints, below).

Does RStudio have a debugger?

R comes with a simple set of debugging tools that RStudio amplifies. You can use these tools to better understand code that produces an error or returns an unexpected result. Usually this will be your own code, but you can also examine the functions in R or one of its packages.


1 Answers

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.

like image 102
IRTFM Avatar answered Sep 20 '22 12:09

IRTFM