get filename and path of `source`d file

前端 未结 6 1753
心在旅途
心在旅途 2020-12-08 08:20

How can a sourced or Sweaved file find out its own path?

Background:

I work a lot with .R scripts or .Rnw files. My projects are o

6条回答
  •  [愿得一人]
    2020-12-08 08:55

    Starting from gsk3's Seb's suggestions, here's an idea:

    • the combination of username (login) and IP or name of the computer could be used to select the right directory.

    That leads to something like:

        setwd (switch (paste (Sys.info () [c ("user", "nodename")], collapse="."), 
               user.laptop  = "~/Messungen",
               user2.server = "~/Projekte/Projekt/",
               ))
    

    So there is an automatic solution, that

    • works with source
    • works with Sweave
    • even works for interactive sessions where the commands are sent line by line

    • the combination of user and nodename of course needs to be specific

    • the paths need to be edited by hand, though.

    Improvements welcome!


    Update:

    Gabor Grothendieck answered the following to a related question on r-help today:

    this.dir <- dirname(parent.frame(2)$ofile)
    setwd(this.dir)
    

    which will work for source.


    Another update: I now do most of the data analysis work in RStudio. RStudio's projects basically solve the problem: RStudio changes the working directory to the project root directory every time I switch between projects.

    I can therefore put the project directory as far down my directory tree as I want (and the students can also put their copy wherever they want) and sync the data files and scripts/.Rnws via version control (We use a private git server). The RStudio project files are kept out of the version control, i.e. .gitignore contains .Rproj.user.

    Obviously, within the project, the directory structure needs to be synchronized.

提交回复
热议问题