Reputation: 1058
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")
They are both in the same directory. When I run it from that directory using Rscript --vanilla test.R
, it works fine. I would like to create multiple subdirectories (run1, run2, run3, ...) and run my original scripts for different parameter values. Suppose I cd run1
and then try to run the script, I get
C:\Downloads\scripts\run1>Rscript --vanilla ..\test.R
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
Calls: source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'incl.R': No such file or directory
Execution halted
How do I get this to work?
Upvotes: 1
Views: 3574
Reputation: 15897
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
.
Upvotes: 3