[R] how to know where you've been sourced from

Alexander Shenkin ashenkin at ufl.edu
Wed Sep 26 20:39:34 CEST 2012


Hello All,

I need a script to perform different actions depending on the file from
which it was source()'d.  Thus, my script needs a way to figure out from
whence it was sourced.

There seems to be some relevant information in sys.calls() (see below).
 However, I need to get at the name of the file that directly source the
file in question.  That is, just one level above.  For example, in the
example below, test.r needs to know that it was called by source_test.r.
 In this example, the information is in sys.calls()[[4]].  But, if there
are other calls in the stack, I don't imagine it will always be in
sys.calls()[[4]].  Is there a consistent place in sys.calls() or
elsewhere I can look for the sourcing file name?

thanks,
allie


> cat("print(sys.calls())",file="test.r")
> cat("source(\"test.r\")",file="source_test.r")
> cat("source(\"source_test.r\")",file="source_test_parent.r")
> source("source_test_parent.r")

[[1]]
source("source_test_parent.r")

[[2]]
eval.with.vis(ei, envir)

[[3]]
eval.with.vis(expr, envir, enclos)

[[4]]
source("source_test.r")

[[5]]
eval.with.vis(ei, envir)

[[6]]
eval.with.vis(expr, envir, enclos)

[[7]]
source("test.r")

[[8]]
eval.with.vis(ei, envir)

[[9]]
eval.with.vis(expr, envir, enclos)

[[10]]
print(sys.calls())



More information about the R-help mailing list