0

What R command can be used to recover the location of the source file that is executed?

For example, using Rstudio, create a file "/home/myname/mycode/test.R" that contains the single line of code:

sprintf("Output: %s", getwd())

On Ubuntu, if I load this file into Rstudio, and press "Run" I get

Output: /home/myname

If I run the file from the command line as below I get:

cd /home/myname

R -f /home/myname/mycode/test.R

Output: /home/myname

However I'm looking for an alternative command to getwd() that returns the location of the executed script, in this case, I want:

Output: /home/myname/mycode/test.R

or

Output: /home/myname/mycode

=============================

The reason of this question, while doing active development I use R script files hat share common directories and source other files in the same directory. I develop on different machines that each use different root directory locations for the depository. I don't want to go to the extent of wrapping those files into a R package.

Thanks!

Andreas Rhode
  • 201
  • 2
  • 2
  • 2
    IMHO, what you're trying to do is much more difficult than creating a simple package. – Joshua Ulrich Jan 28 '14 at 18:55
  • you could use environment variables, e.g. `file_path(Sys.getenv($HOME), "mycode/test.R")` or `file_path(Sys.getenv($MYCODE), "test.R")` etc. – flodel Jan 28 '14 at 18:57
  • The other answer to the related question "Rscript: Determine path of the executing script" does not address running the script within R studio. Seems like the solution of requiring a special environment variable is a good compromise. – Andreas Rhode Jan 29 '14 at 14:50

0 Answers0