【问题标题】:How to pass in function parameters for an R file when run from terminal?从终端运行时如何传入 R 文件的函数参数?
【发布时间】:2016-02-20 21:15:26
【问题描述】:

我的计算机上有一个要从命令行运行的文件。该文件将在其中发生一些事情+一个函数。

例如,我有一个全局变量 start_value=10,然后我在 Rscript 中调用了一个函数。我想在传递参数的同时运行这个脚本

我试图在网上找到如何做到这一点,但我没有运气。
我收到此错误:

  Error in help_function(x, y) : object 'x' not found

这样运行时:

    Rscript helpme.R 100 10

-

  ##?? saw this someplaces when searching, but couldn't get it to work
 args = commandArgs(trailingOnly=TRUE)

 starting_value=10

 help_function = function(x,y){


     division =x/y
     answer=starting_value + division
 return(answer)
}

 help_function(x,y)

【问题讨论】:

  • 您需要从args 中挑选出参数,并在必要时对其进行处理,as for example here
  • 很明显,如果您从未在脚本中定义它,R 将无法找到 x...

标签: r function terminal rscript


【解决方案1】:

commandArgs 函数返回一个字符向量以及传递给命令行的参数(trailingOnly = TRUE 删除了"RScript helpme.R" 部分)。

在你的情况下:

args <- commandArgs(trailingOnly = TRUE)

# parse your command line arguments
x <- as.numeric(args[1]) # args[1] contains "100"
y <- as.numeric(args[2]) # args[2] contains "10"

# ...continue with your script here

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 2016-05-16
    • 1970-01-01
    • 2012-09-17
    • 2021-02-06
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多