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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to