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

Duncan Murdoch murdoch.duncan at gmail.com
Wed Sep 26 20:45:23 CEST 2012


On 26/09/2012 2:39 PM, Alexander Shenkin wrote:
> 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?

Look in the global variable you created just before you sourced it, e.g.

MyNameIs <- "foo.R"
source("bar.R")

>
> 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())
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list