I am working out some tutorials in R. Each R code is contained in a specific folder. There are data files and other files in there. I want to open the .r
file and source it such that I do not have to change the working directory in Rstudio as shown below:
Is there a way to specify my working directory automatically in R.
In case you use UTF-8 encoding:
You need to install the package rstudioapi if you haven't done it yet.
The solution
not working for me.
I'm using a brute force algorithm, but works:
More easy when searching a directory:
I was just looking for a solution to this problem, came to this page. I know its dated but the previous solutions where unsatisfying or didn't work for me. Here is my work around if interested.
works for me but if you don't want to use rstudioapi and you are not in a proyect, you can use the symbol ~ in your path. The symbol ~ refers to the default RStudio working directory (at least on Windows).
If your RStudio working directory is "D:/Documents",
setwd("~/proyect1")
is the same as setwd("D:/Documents/proyect1").Once you set that, you can navigate to a subdirectory:
read.csv("DATA/mydata.csv")
. Is the same asread.csv("D:/Documents/proyect1/DATA/mydata.csv")
.If you want to navigate to a parent folder, you can use
"../"
. For example:read.csv("../olddata/DATA/mydata.csv")
which is the same asread.csv("D:/Documents/oldata/DATA/mydata.csv")
This is the best way for me to code scripts, no matter what computer you are using.
I understand this is outdated, but I couldn't get the former answers to work very satisfactorily, so I wanted to contribute my method in case any one else encounters the same error mentioned in the comments to BumbleBee's answer.
Mine is based on a simple system command. All you feed the function is the name of your script:
The output from the function would look like
"/Users/you/Path/To/Script"
. Hope this helps anyone else who may have gotten stuck.To get the location of a script being sourced, you can use
utils::getSrcDirectory
orutils::getSrcFilename
. So changing the working directory to that of the current file can be done with:This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use
rstudioapi::getActiveDocumentContext
.This second solution requires that you are using RStudio as your IDE, of course.