Set working directory to file location in R

1.2k Views Asked by At

I have a folder, say program, which contains all my scripts, data, etc:

  • main.R

  • src/

    • other_file_1.R
    • other_file_2.R
  • data/

    • some_dataset.csv
    • output/
      • stuff.txt
      • other_stuff.png
  • logs/

  • Readme.txt

The person who receives my folder, opens it and runs main.R.

Now, since I wanna be able to read and write in the subfolders shown above, I want to set the working directory to the program folder from the main.R script.

So I do this:

install.packages("rstudioapi")
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

but I get the following error:

Error in getActiveDocumentContext() : 
could not find function "getActiveDocumentContext"

I've also tried loading the library:

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

but I get the same error.

0

There are 0 best solutions below