Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

metaprogramming - 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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...