从终端 运行 时如何为 R 文件传递函数参数?
How to pass in function parameters for an R file when run from terminal?
我的计算机上有一个文件,我想从命令行 运行。这个文件里面会发生一些事情+一个函数。
例如,我有一个全局变量 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)
commandArgs
函数 returns 一个带有参数的字符向量传递给命令行(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
我的计算机上有一个文件,我想从命令行 运行。这个文件里面会发生一些事情+一个函数。
例如,我有一个全局变量 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)
commandArgs
函数 returns 一个带有参数的字符向量传递给命令行(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