下面是一个有几个脚本的例子
test.R ==>
source("incl.R", chdir=TRUE)
print("test.R - main script")
incl.R ==>
print("incl.R - included")它们都在同一个目录中。当我使用Rscript --vanilla test.R从那个目录运行它时,它工作得很好。我想创建多个子目录(run1,run2,run3,.)并为不同的参数值运行我的原始脚本。假设我cd run1,然后尝试运行脚本,我得到
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我怎么才能让这个起作用?
发布于 2015-05-15 18:00:33
我不确定我是否正确地解决了你的问题。我假设您的脚本test.R和incl.R位于同一个文件夹中,然后使用其他文件夹中的Rscript运行test.R。test.R应该知道test.R (因此是incl.R)存储在哪里,然后找到源incl.R。
诀窍是,必须将脚本test.R的完整路径作为调用Rscript的参数。可以使用commandArgs获取这个参数,然后从它构造incl.R的路径:
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)在问题中的示例中,您可以通过Rscript --vanilla ..\test.R调用脚本。然后,args将是包含元素“-file=../test.R”的字符向量。使用grep,我获取这个元素,然后使用gsub从它获取路径“../incl.R.R”。然后,可以在source中使用此路径。
https://stackoverflow.com/questions/30264144
复制相似问题