【问题标题】:create and run a batch file of R scripts from command prompt only if a condition satisfies仅当条件满足时,才从命令提示符创建和运行 R 脚本的批处理文件
【发布时间】:2016-03-07 17:38:51
【问题描述】:

我需要做以下事情:

1) 从 R 脚本(我们称之为 sample1.r)中,我将得到一个变量 updated 和一个向量 dates
2) 现在我需要做的是,如果满足条件(即if updated == 1),我需要通过从向量dates 传递参数来运行R 脚本的批处理文件。 R 脚本的批处理文件看起来像这样。

Rscript D:/sample2.r "2015-05-01 00:00:00" dates[1] dates[2]    #statements 1
Rscript D:/sample2.r "2015-05-11 00:00:00" dates[2] dates[3]    #statements 2
Rscript D:/sample2.r "2015-05-21 00:00:00" dates[3]             #statements 3  

正如您在上面看到的,如果条件满足,我将创建一个批处理文件。首先,我得到一个向量dates,然后将此向量的元素作为arguments 传递给脚本sample.r。我将 2 个参数传递给前 2 次运行,将 1 个参数传递给第 3 次运行。

作为解决方案,我可以使用paste0 函数在 R 本身中创建这些语句,但之后如何将这些语句转换为批处理文件并仅在条件满足时从命令提示符触发它们?可能有更简单的解决方案,但我不知道。有人可以帮我吗?

【问题讨论】:

    标签: r batch-file rscript


    【解决方案1】:

    您可以使用source调用外部脚本。

    if(update == 1){
        source("D:/sample2.r")
        FunctionName("2015-05-01 00:00:00", dates[1], dates[2])
        FunctionName("2015-05-11 00:00:00", dates[2], dates[3])
        FunctionName("2015-05-21 00:00:00", dates[3])
    }
    

    source 将调用并运行外部脚本。如果您编写的脚本没有函数,它将完全运行该脚本。在这种情况下,我建议将其拆分为函数。这样您就可以在该脚本中调用您想要调用的任何函数名称。您可以只编写一个 if 语句来调用脚本和函数。 注意:如果两个脚本包含相同的函数名,这可能会产生冲突,例如主要。

    如果你想调用脚本并传递你的局部变量:

    source("D:/sample2.r", local=TRUE)
    

    但是如果你想按照你之前提到的方式调用脚本,你可以使用system

    if(update == 1){
        system(paste('Rscript D:/sample2.r "2015-05-01 00:00:00"', dates[1], dates[2], sep=" "))
        system(paste('Rscript D:/sample2.r "2015-05-11 00:00:00"', dates[2], dates[3], sep=" "))
        system(paste('Rscript D:/sample2.r "2015-05-21 00:00:00"', dates[2], sep=" "))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多