[R] Looking up the directory a file is located in

Duncan Murdoch murdoch.duncan at gmail.com
Thu Nov 18 19:34:59 CET 2010


On 18/11/2010 11:56 AM, Cliff Clive wrote:
> Thanks, Gabor!  So far I like this one best:
> https://stat.ethz.ch/pipermail/r-help/2005-November/082347.html
>
> So if my script is called "myRscript.r", I can do the following:
>
>
> this.file = parent.frame(2)$ofile
> this.dir = gsub("/myRscript.r", "", this.file)
> setwd(this.dir)
>
>
> This will set the working directory to the the directory that myRscript.r
> lives in, no matter where I move the script.  It's nice that it can be done
> in only three lines of code, although it's not yet a perfect solution, since
> it won't work if I change the name of the script.  But that's easy to take
> care of if I just do some slightly more sophisticated string manipulation
> (which I'm terrible at doing off the top of my head).

You can use the dirname() function to remove the filename from the path, 
you don't need to know the filename.  But you are making some strong 
assumptions in this code that may not hold:

  - that your script was invoked by source(), rather than piping into R, 
or using Rscript, or R CMD BATCH...
  - that source() has a local variable named ofile (which it does, but 
it might not in the future)

I would say it's bad practice for your script to change directories and 
not restore the old one, but that's a matter of taste.

I think the other solutions you were offered are better than this one.

Duncan Murdoch



More information about the R-help mailing list