get filename and path of `source`d file

前端 未结 6 1756
心在旅途
心在旅途 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 09:00

    An additional problem is that the working directory is a global variable, which can be changed by any script, so if your script calls another script, it will have to set the wd back. In RStudio I use Session -> Set Working Directory -> To Source File Location (I know, it's not ideal), and then my script does

    wd = getwd ()
    ...
    source ("mySubDir/myOtherScript.R", chdir=TRUE); setwd (wd)
    ...
    source ("anotherSubDir/anotherScript.R", chdir=TRUE); setwd (wd)
    

    In this way one can maintain a stack of working directories. I would love to see this implemented in the language itself.

提交回复
热议问题