If you think the solution given doesn't work, then presumably you don't just want to know the path when you source the file, but permanently for any objects it creates.
The srcref
system provides at least some of what you want, if options(keep.source=TRUE)
Eg:
> source("~/Downloads/main.R")
> getSrcFilename(svy_vglm,full.names=TRUE)
[1] "svgam.R"
> getSrcFilename(f)
[1] "main.R"
> getSrcDirectory(f)
[1] "/Users/tlum005/Downloads"
The directory is the directory by which the file was looked up: if you just did source("main.R")
, the directory would be .
rather than its absolute form.
Rewriting your main.R
you might get
f = function() {
cat(getSrcDirectory(f))
}
f()
Two weaknesses here are that srcref attributes are copied by assignment and f()
relies on knowing its own name. If you did
g<-f
g()
rm(f)
g()
you might want the two calls to g()
to both return errors (since g()
wasn't sourced) or both to return the directory, but you wouldn't want one of each. This can be worked around in this case with sys.function()
: if main.R
is
f = function() {
cat(getSrcDirectory(sys.function()))
}
f()
the assignment works
> source("~/Downloads/main.R")
/Users/tlum005/Downloads
> f()
/Users/tlum005/Downloads
> g<-f
> g()
/Users/tlum005/Downloads
> rm(f)
> g()
/Users/tlum005/Downloads
I wouldn't advocate using this method -- I can't think of a situation where you wouldn't be better off just putting the source code somewhere better organised -- but I think it does answer the question.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…