How to get R to recognize your working directory as its working directory?

Viewed 84668

I use R under Windows on several machines.

I know you can set the working directory from within an R script, like this

setwd("C:/Documents and Settings/username/My Documents/x/y/z")

... but then this breaks the portability of the script. It's also annoying to have to reverse all the slashes (since Windows gives you backslashes)

Is there a way to start R in a particular working directory so that you don't need to do this at the script level?

10 Answers

I put the following line in front of my scripts and it allows me to work across my computers.

setwd(path.expand("~/path/to/working/directory/") )

where ~ is = to your home directory.

Sys.setenv(HOME = "path") or Sys.setenv(R_USER = "path") can both set the home directory.

In my case, I work on several windows boxes, each have fairly different directory structures, but by setting the home directory properly I can sync code between computers and have them run properly on each one since where I run my R projects have similar directory structures.

To set working directory in R Studio: Refer detailed slide deck with screen-shots here.

  1. Using setwd(): windows users would need to replace backward slashes '' with forward slashes '/' or double backward slashes '\' You can do the former using find & replace (Short-cut: Ctrl+F)
  2. Another option: Go to Session --> set working directory --> choose working directory & browse the folder which you want to set as the working directory, click on open
  3. Quickest method (my favorite) use the shortcut 'Ctr+Shift+H' (on windows system), browse the folder which you want to set as the working directory, click on open

To set a permanent working directory (when not in a project) in R Studio: Refer my quick video on the same: https://youtu.be/hMjzO4bAi70

Go to Tools --> Global Options --> R General [Basic] --> Default Working Directory (when not in a project) browse the folder which you want to set as the working directory, click on 'Apply' and 'OK'

enter image description here

However, the efficient & better way to organize your work is to create projects & use version control.

Put a shortcut for the R gui into your desired directory. Right-click and look at the shortcut properties. Delete the entry for "Start In" and click OK. When you launch the R gui from this shortcut the default directory will be the folder from which you have launched. Copy/paste this shortcut wherever you desire.

Related