R command for setting working directory to source file location in Rstudio

163,456

Solution 1

To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename. So changing the working directory to that of the current file can be done with:

setwd(getSrcDirectory()[1])

This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext.

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

This second solution requires that you are using RStudio as your IDE, of course.

Solution 2

I know this question is outdated, but I was searching for a solution for that as well and Google lists this at the very top:

this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)

put that somewhere into the file (best would be the beginning, though), so that the wd is changed according to that file.

According to the comments, this might not necessarily work on every platform (Windows seems to work, Linux/Mac for some). Keep in mind that this solution is for 'sourcing' the files, not necessarily for running chunks in that file.

see also get filename and path of `source`d file

Solution 3

For rstudio, you can automatically set your working directory to the script directory using rstudioapi like that:

library(rstudioapi)

# Getting the path of your current open file
current_path = rstudioapi::getActiveDocumentContext()$path 
setwd(dirname(current_path ))
print( getwd() )

This works when Running or Sourceing your file.

You need to install the package rstudioapi first. Notice I print the path to be 100% sure I'm at the right place, but this is optional.

Solution 4

dirname(rstudioapi::getActiveDocumentContext()$path)

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).

RStudio options

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 as read.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 as read.csv("D:/Documents/oldata/DATA/mydata.csv")

This is the best way for me to code scripts, no matter what computer you are using.

Solution 5

This answer can help:

script.dir <- dirname(sys.frame(1)$ofile)

Note: script must be sourced in order to return correct path

I found it in: https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

The BumbleBee´s answer (with parent.frame instead sys.frame) didn´t work to me, I always get an error.

Share:
163,456

Related videos on Youtube

Stat-R
Author by

Stat-R

Updated on February 22, 2022

Comments

  • Stat-R
    Stat-R about 2 years

    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:

    enter image description here

    Is there a way to specify my working directory automatically in R.

  • nico
    nico over 11 years
    For sure RStudio does not make that assumption.
  • IRTFM
    IRTFM over 11 years
    It behaves the way I described it on my machine. I have not done anything special to the RStudio Preferences.
  • nico
    nico over 11 years
    Does not do that on Linux :)
  • WetlabStudent
    WetlabStudent over 9 years
    "When launched through a file association" is the key condition here. Some people might be launching Rstudio via a shortcut or a command in the terminal. You need to open the file and have the default for opening .R files be Rstudio. If you open Rstudio first (then open the file) it will not work as described. Through a file association, the above answer works in windows and mac (possibly not linux as @nico points out - but I can't verify this as I don't have a linux machine).
  • tumultous_rooster
    tumultous_rooster about 9 years
    didn't work for me either: Error in dirname(parent.frame(2)$ofile) : a character vector argument expected
  • BumbleBee
    BumbleBee about 9 years
    did you look in the linked thread as well? I don't know any solution by now, but there are other people with similar errors. Maybe it is OS-specific? I used it on Windows 8, but some report it didn't work on mac ...
  • patapouf_ai
    patapouf_ai almost 9 years
    Same problem here as @Matt O'Brien on Linux.
  • HappyCoding
    HappyCoding over 8 years
    running on windows, same proble here as @bisounours_tronconneuse
  • Rich Scriven
    Rich Scriven about 8 years
    Error: 'getActiveDocumentContext' is not an exported object from 'namespace:rstudioapi' also in Ubuntu 14.04
  • Lamothy
    Lamothy about 8 years
    Maybe you can try install rstudioapi package first.
  • Lamothy
    Lamothy about 8 years
    That's strange. I'm using R-3.2.4 in a 32-bit ubuntu 14.04. I hope it is not because of operating system or different versions of R.
  • Stat-R
    Stat-R about 8 years
    your own answer at stackoverflow.com/a/35842176/1247080 works (one must include the dirname though). I added it
  • m-dz
    m-dz almost 8 years
    Working perfectly if sourced.
  • Caner
    Caner over 7 years
    This just gives your home directory (where your shell starts).
  • Taz
    Taz over 7 years
    It gives path to directory where script you run is.
  • Andru
    Andru over 7 years
    Doesn't work for me. I get Error: 'getActiveDocumentContext' is not an exported object from 'namespace:rstudioapi'
  • Richie Cotton
    Richie Cotton over 7 years
    @Andru are you using a recent version of RStudio? It won't work in other IDEs (including RGUI) or old versions of RStudio. Similarly, make sure you have the latest version of the rstudioapi package.
  • PeterVermont
    PeterVermont about 7 years
    pwd stands for present working directory. This will set the directory to whatever the current directory of the shell is.
  • jodis
    jodis almost 7 years
    Is there a reason why you don't just use setwd( dirname(filepath) ) ?
  • Contango
    Contango almost 7 years
    Worked for me in RStudio v1.0.143 on Windows 10. If you select "Source on save", it will work just fine (you can print out the detected directory with "cat"). If you select the lines then execute them, then the result is null.
  • Megatron
    Megatron over 6 years
    Note that when you run getActiveDocumentContext() in the console within RStudio, the path is reported as ''. However, if you run the line of code in the editor portion, it will execute as expected. This may address @Andru 's comment
  • Giacomo
    Giacomo over 6 years
    I run setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) on a Mac and I got Error: 'getActiveDocumentContext' is not an exported object from 'namespace:rstudioapi'
  • Richie Cotton
    Richie Cotton over 6 years
    @giac_man It sounds like you are using a very old version of the rstudioapi package. Try updating to the latest one.
  • tavalendo
    tavalendo almost 6 years
    @BumbleBee I think this answer should be edited based on these comments: mention that this works for windows and is not tested for other OS. Thanks.
  • tavalendo
    tavalendo almost 6 years
    Error in setwd(dirname(current_path)) : cannot change working directory
  • tavalendo
    tavalendo almost 6 years
    Error in setwd(dirname(path)) : cannot change working directory
  • tavalendo
    tavalendo almost 6 years
    Problem with this solution is that is very slow. Searching for all files and store in a variable also takes up a lot of memory.
  • gagarine
    gagarine almost 6 years
    @helmo check your user has write permission on the target directory.
  • bmosov01
    bmosov01 almost 6 years
    This works for me on a Mac when sourcing a file. However, as @Contango pointed out above, it will not work when executing the code interactively by highlighting a chunk and pressing Command + Return. In this case, since you're not sourcing a file, there is no source file to pull the working directory from. The answer need not specify platform-specific caveats.
  • Sandu Ursu
    Sandu Ursu over 4 years
    I get: Error in setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) : cannot change working directory; Apparently because I run it in the console. It runs well in the script.
  • Richie Cotton
    Richie Cotton over 4 years
    @SanduUrsu Correct: the console is not an active document, so rstudioapi::getActiveDocumentContext()$path is "".
  • filups21
    filups21 over 4 years
    setwd(getSrcDirectory()[1]) didn't work for me when I sourced the file. The rstudioapi solution worked.
  • Mr Coder
    Mr Coder over 4 years
    ``` Error in setwd(dirname(path)) : cannot change working directory`` your solution not working please check your answer
  • BumbleBee
    BumbleBee about 4 years
    @MrSCoder Do you have any error message or alike? Maybe the solution is already outdated. Did you try another solution here?
  • mjs
    mjs about 4 years
    @RichieCotton is there a way to automatically jump to that working directory and showing it content in 'Files' tab in RStudio?
  • Richie Cotton
    Richie Cotton about 4 years
    @mjs At the top of the console, you should see the current working directory. To the right of that is a small arrow. Click that to show the current working directory in the file browser.
  • mjs
    mjs about 4 years
    @RichieCotton, yes, nice feature I didn't know about, thanks. But if I have multiple scripts open in the Source window its name is displayed only after I ran one (and then I still have to click on the arrow). It would be best the Files view switches automatically to that of the viewed script.
  • BroVic
    BroVic about 4 years
    pwd also works in PowerShell (which is currently considered the default shell on Windows), where it's an alias for Get-Location.
  • BroVic
    BroVic about 4 years
    Thanks for this answer. The location of the current script can be harnessed by placing a call to here::set_here() in the source.