Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 771
Dan Goldstein Avatar asked Sep 08 '09 17:09

Dan Goldstein


People also ask

Why can't I set my working directory in R?

Unfortunately, the RStudio console returns the error message “cannot change working directory”. The reason for this is that the directory we are trying to access does not exist. We might have specified the folder name wrong, or the path before the folder name is not existing.

Which function is used to get the working directory in R?

getwd(): The getwd() method is used to gather information about the current working pathname or default working directory.

How do I set the working directory in R from source file?

Step 1) Click on the Session tab. Step 2) Click on Set Working Directory > To Source File Location. Afterwards, you working directory will be changed to the location of your source file.


2 Answers

You should copy shortcut to R (R.lnk file) to desire folder. Then in "Properties" (right mouse button -> last option) delete anything in field "Start in..." in second tab ("Shortcut"?). If you start R with this shortcut working directory will be that one where the shortcut is.

I don't have english version of Windows so I'm not sure about field names, but they should be easy to find.

Similar questions were in R-windows-faq:

2.5 How do I run it?

2.10 How can I keep workspaces for different projects in different directories?

2.14 What are HOME and working directories?

In 2.14 is mentioned that

The working directory is the directory from which Rgui or Rterm was launched, unless a shortcut was used when it is given by the `Start in' field of the shortcut's properties.

like image 97
Marek Avatar answered Sep 28 '22 02:09

Marek


You could use an environmental variable. This can work with Sys.getenv() and Sys.setenv(). For instance:

> Sys.setenv(R_TEST="testit") > Sys.getenv("R_TEST")   R_TEST  "testit"  

If you sent the variable in your script, you should be able to access it from within, and then call setwd() on that output.

like image 45
Shane Avatar answered Sep 28 '22 02:09

Shane