0

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.

IDK
  • 359
  • 1
  • 16
  • 1
    Changing the working directory is generally considered to be [poor practice](https://stackoverflow.com/questions/73489216/choose-working-directory-in-code-option-of-r-chunk#73489216). Better to (determine the actual working directory and then) construct relative paths to the desired resources. – Limey Aug 28 '22 at 17:58
  • Are you actually running the code in the RStudio IDE? The "could not find function" error does not seem like the one you should be getting if you actually called `rstudioapi::getActiveDocumentContext()`. Are you sure that's the code you are running? What verison of R are you running? But I would second the fact that you should not programmatically set the working directory. Better to use something like an RStudio project or there [here](https://here.r-lib.org/) package to deal with relative paths. – MrFlick Aug 28 '22 at 19:11

0 Answers0