【问题标题】:running an R script from another directory从另一个目录运行 R 脚本
【发布时间】:2015-07-27 15:39:02
【问题描述】:

这是一个包含几个脚本的示例

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

如何让它工作?

【问题讨论】:

    标签: r rscript


    【解决方案1】:

    我不确定我是否正确理解了您的问题。我假设您的脚本 test.Rincl.Rsame 文件夹中,然后使用其他文件夹中的 Rscript 运行 test.Rtest.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”。然后可以在source 中使用此路径。

    【讨论】:

    • 感谢您的回复。您确实正确理解了这个问题。有没有办法不对路径进行硬编码(“../incl.R”)?是否可以以编程方式获取 test.R 的路径,然后在获取其他脚本时添加该路径?
    • 我重新制定了答案,使得路径不再被硬编码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2023-01-13
    • 2016-09-03
    相关资源
    最近更新 更多