Here\'s an example with a couple of scripts
test.R ==>
source(\"incl.R\", chdir=TRUE)
print(\"test.R - main script\")
incl.R ==>
print(\"incl.R - included
I am not sure that I unserstand your problem correctly. I assume that you have your scripts test.R
and incl.R
in the same folder and then run test.R
using Rscript
from some other folder. test.R
should figure out where test.R
(and thus incl.R
) is stored and then source incl.R
.
The trick is that you have to put the full path to the script test.R
as an argument to your call of Rscript
. It is possible to get this argument using commandArgs
and then construct the path to incl.R
from it:
args <- commandArgs(trailingOnly=FALSE)
file.arg <- grep("--file=",args,value=TRUE)
incl.path <- gsub("--file=(.*)test.R","\\1incl.R",file.arg)
source(incl.path,chdir=TRUE)
In your example in the question, you call the script by Rscript --vanilla ..\test.R
. args
will then be a character vector that contains the element "--file=../test.R". With grep
I grab this element and then use gsub
to obtain the path "../incl.R" from it. This path can then be used in source
.