4

When I start R session from some directory, R automatically loads the corresponding workspace (if it exists). After I finish to work in this workspace I can decide if I want to modify (save) the current workspace. This logic is simple and clear.

What I do not understand, is what happens if I start R from some directory and then change the working directory by setwd(). As far as I understood the workspace corresponding to the new working directory will not be "loaded". I still see the variables and history from the previous working directory. Why?

Second, when I quit() R, I replace the work-space image corresponding to the "new" working directory by the workspace corresponding to the "old" directory. Do I interpret the behavior correctly? What is the logic behind this behavior? Can I switch to another work-space from R session?

Roman
  • 124,451
  • 167
  • 349
  • 456
  • We can disable automatic restore options for project/sourcedocs/.RData from menu `Tools > Options`. Saving environment as [a Project](https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects) is great when we want to come back to exactly where we left off. – zx8754 Jun 11 '15 at 07:12

1 Answers1

3

Workspaces are stored in .RData files and are automatically loaded from current working directory when you start R. But working directory itself (and setwd() function that sets it) has nothing to do with workspace. You can load any workspace by explicitly specifying any .RData file:

load("c:/project/myfile.RData")

or

setwd("c:/project/")
load()
cyberj0g
  • 3,707
  • 1
  • 19
  • 34
  • Yes, because `setwd()` is ran after any `load()`. –  Jun 11 '15 at 05:45
  • If you use Rstudio or statet and create project you should not be worry about the workspace. – user1436187 Jun 11 '15 at 06:04
  • 1
    RStudio is asking whether you wish to save workspace image before quitting. Personally, I prefer not to save the workspace most of the time, because it quickly becomes huge when you researching something with big datasets, and takes many time\space to save-load. – cyberj0g Jun 11 '15 at 06:09
  • When I interpreted the results of my play-around correctly, the working directory and works-spaces are not totally "orthogonal" (independent). I have seen that the image of the current works spaces is set in the working directory that I set. Let say I started R from directory `test1` the corresponding work-space has been loaded automatically, then I used `setwd` to set the working directory value to `test2` and then, when I quit R, the current work-space is saved in `test2` directory. – Roman Jun 11 '15 at 07:19
  • Yes, `save()` and `load()` functions that are called under the hood when R is started\quitted are using current WD, but changing WD itself doesn't cause any workspace manipulations. – cyberj0g Jun 11 '15 at 07:24