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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With