[R] Looking up the directory a file is located in
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Thu Nov 18 17:03:19 CET 2010
On Thu, Nov 18, 2010 at 3:26 PM, Cliff Clive <cliffclive at gmail.com> wrote:
>
> So it sounds like the best we can do in R is to keep track of the script in a
> sort of master file that runs the script, and set the working directory in
> the master. Is that accurate?
Errr no. Maybe. What?
Your script is somewhere. Something is calling it. The thing that
calls it knows where it is. The thing that calls it is then
responsible for telling the script where it is. For example:
here = "C:/Fnord/"
source("C:/Fnord/script.R")
now the script in C:\Fnord\script.R looks at 'here' and finds its
data files by pasting 'data.txt' onto the value of 'here'.
This is of course still a fairly bad way of doing things. Better to
write functions that can live _anywhere_ and tell them where to find
their data. So instead of the above, you should end up with:
source("C:/MyLibrary/mycode.R")
nowProcess("C:/Fnord")
where nowProcess is a function that takes a directory to work on as
its first parameter.
But EVEN better still is to write a package. Then you do:
library(myPackage)
nowProcess("C:/Fnord")
> In Python any time you run a script, there is a built-in "__file__" variable
> that can tell you the file name of the script itself. It would be nice to
> have a feature like this in R.
Indeed. Also, I'd like to get rid of curly brackets from R and use
indentation, and have a neater class mechanism... Perhaps decorators
for functions... Hmm...
Barry
More information about the R-help
mailing list