2.6 Save R Workspace

If you want to saves all objects in your work space, use save.image(). It will creates an image of your current variables and functions, and saves them to a file called .RData. When R next loads, objects stored in this image are by default restored.

This sounds convenient, however, you do NOT want to do this because this corrupt reproducibility of your project. ❌

You want to start from a clean slate very time. ✅

It is suggested change RStudio Global Options to

  • not “restore .RData into workspace at startup”, and
  • never “save workspace to .RData on exit”.

RStudio workspace

In case you do feel the need to save the workspace, use the following cmd.

save.image(file = ".RData", version = NULL, ascii = FALSE, compress = !ascii, safe = TRUE)

## save current workspace ##
f_name <- "RImage/TCR_2023-05-09.RData"
f_name
save.image(f_name)
# load(f_name)

Q: Can I save the loaded packages in the current session/workspace?
A: The workspace is for objects like data and functions. Starting R with particular packages loaded is what your .Rprofile file is for, and you can have a different one in each directory. But I’d recommend not saving anything between r sessions and instead recreate it all using code. This is much more likely to lead to reproducible results.

History

When you quit a project, .Rhistory is automatically written to the project directory unless you opt out to. It contains a history of all of the commands that you have sent to the R console in this session.