[R] Find Source File Corresponding to Sourced Function

Duncan Murdoch murdoch at stats.uwo.ca
Thu Feb 11 04:53:38 CET 2010


On 10/02/2010 7:30 PM, Scott Stephens wrote:
> I've noticed that when you debug a function that was loaded into the
> workspace using the source function, it prints the location of the
> file from which the function was sourced.  Is there a way to get that
> same information without debugging the function?

Here's a function to do it.  Probably we should have something like this 
in utils, but I've never got around to writing it.

Put these into "test.R":
-------------------------
f <- function(x) {
   x <- x^2
   x
}

fnsrc <- function(f) {
   srcref <- attr(body(f), "srcref")
   if (is.null(srcref)) stop("No source reference")
   srcfile <- attr(srcref[[1]], "srcfile")
   startline <- srcref[[1]][1]
   paste(srcfile$filename, startline, sep="#")
}
-------------------------

Then:

 > fnsrc(f)
[1] "test.R#1"
 > fnsrc(fnsrc)
[1] "test.R#6"

Duncan Murdoch



More information about the R-help mailing list