Skip to content
Prev 376873 / 398502 Next

Genuine relative paths with R

Hi Gabor,
?

  1.  By definition the relative path (I'm excluding the absolute path solution for obvious reasons) depends on the current working directory: What if my R script is not located along this current working directory? It won't work.?
  2.  What should I write as an option in this .Rprofile file? An absolute path to the project's root? Plus I don't want the users to choose their working directory: this technicality should be kept hidden from them and be automatic.?

Best regards,?
?
Olivier
________________________________
De : Gabor Grothendieck <ggrothendieck at gmail.com>
Envoy? : samedi 6 octobre 2018 23:33
? : olivier_givaudan at hotmail.com; r-help at r-project.org
Objet : Re: [R] Genuine relative paths with R

1. Assuming you are starting the script from within R, if you want to
keep all the files used by the script together with the script itself
then just source the script using the absolute or relative path to the
script using source(..., chdir = TRUE) as shown below and the script
will run in the directory containing the script. We used an absoluate
path below but a relative path will work too.  In either case the
script itself will not need to use absolute paths and it is portable
to other machines.

  source("/path/to/script.R", chdir = TRUE)

If your script is on your PATH then this would work:

  source(Sys.which("script.R"), chdir = TRUE)

2. Another approach is to define an R option, say root, using the R
options() function to define the root directory of your project.  You
can have a different R option for each project.  Place the options()
statements to set these R options for your various projects in your
.Rprofile, say, and in the script use:

    root <- getOption("root", ".")

to cause it to retrieve the value of the R option root if it is
defined and use the current directory otherwise.  Use a different name
for each project. If the user does not define the R option root it
will be up to them to change directory first.  Again there will be no
use of absolute paths in the script itself and it is portable to other
machines.

What is particularly convenient about this is that it documents where
all the projects are on the  machine right in the .Rproject file so
one always knows where they are.

On Sat, Oct 6, 2018 at 8:25 AM Olivier GIVAUDAN
<olivier_givaudan at hotmail.com> wrote:
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
Message-ID: <VI1PR0202MB335744BC531D2F410931FEBFF5E00@VI1PR0202MB3357.eurprd02.prod.outlook.com>
In-Reply-To: <CAP01uR=FnwBZ=_iet5q0_tZQS4WZ0MjiiY_-kFr_KL9GFwL=ww@mail.gmail.com>