从终端运行时如何传递R文件的函数参数?

时间:2016-02-20 21:15:26

标签: r function terminal rscript

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

例如,我有一个全局变量,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)

1 个答案:

答案 0 :(得分:0)

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