Search code examples
rmetaprogramming

Find the source file containing R function definition


I come from a python background and am trying to get up to speed with R, so please bear with me

I have an R file - util.R with the following lines:

util.add <- function(a,b) a + b
util.sub <- function(a,b) { a - b }

I source it as follows:

source('path/util.R')

I now have two function objects and want to write a function as follows:

getFilePath(util.add)

that would give me this result

[1] "path/util.R"


Solution

  • Digging into the srcref attribute of one of the loaded functions appears to work, if you go deep enough ...

    source("tmp/tmpsrc.R")
    str(util.add)
    ## function (a, b)  
    ##  - attr(*, "srcref")=Class 'srcref'  atomic [1:8] 1 13 1 31 13 31 1 1
    ##   .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x8fffb18> 
    srcfile <- attr(attr(util.add,"srcref"),"srcfile")
    ls(srcfile)
    ## [1] "Enc"           "filename"      "fixedNewlines" "isFile"       
    ## [5] "lines"         "parseData"     "timestamp"     "wd"    
    srcfile$filename
    ## [1] "tmp/tmpsrc.R"
    

    Comments note that this only works out-of-the-box for interactive code, because ...

    Rscript does not load srcrefs by default. A work-around is this code snippet: Rscript -e "options(keep.source = TRUE); source('your_main_file.R')" or set the option keep.source permanently in the .Rprofile file (see ?Startup for details)