get filename and path of `source`d file

前端 未结 6 1755
心在旅途
心在旅途 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:57

    This answer works for source and also inside nvim-R - I have no idea if it works with knitr and similar things. Any feedback appreciated.

    If you have multiple scripts source-ing each other, it is important to get the correct one. That is, the largest i for which sys.frame(i)$ofile exists.

    get.full.path.to.this.sourced.script = function() {    
        for(i in sys.nframe():1) {  # Go through all the call frames,
                                    # in *reverse* order.
            x = sys.frame(i)$ofile
            if(!is.null(x))               # if $ofile exists,
                return(normalizePath(x))  #  then return the full absolute path
        }
    }
    

提交回复
热议问题