bash 中的命令行参数到 Rscript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4547789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
command line arguments in bash to Rscript
提问by samar
I have a bash script that creates a csv file and an R file that creates graphs from that.
我有一个创建 csv 文件的 bash 脚本和一个从中创建图形的 R 文件。
At the end of the bash script I call Rscript Graphs.R 10
在 bash 脚本的末尾我调用 Rscript Graphs.R 10
The response I get is as follows:
我得到的回应如下:
Error in is.vector(X) : subscript out of bounds
Calls: print ... <Anonymous> -> lapply -> FUN -> lapply -> is.vector
Execution halted
The first few lines of my Graphs.R are:
我的 Graphs.R 的前几行是:
#!/bin/Rscript
args <- commandArgs(TRUE)
CorrAns = args[1]
No idea what I am doing wrong? The advice on the net appears to me to say that this should work. Its very hard to make sense of commandArgs
不知道我做错了什么?在我看来,网上的建议是说这应该有效。很难理解commandArgs
采纳答案by moinudin
With the following in args.R
在 args.R 中有以下内容
print(commandArgs(TRUE)[1])
and the following in args.sh
以及 args.sh 中的以下内容
Rscript args.R 10
I get the following output from bash args.sh
我得到以下输出 bash args.sh
[1] "10"
and no error. If necessary, convert to a numberic type using as.numeric(commandArgs(TRUE)[1]).
并且没有错误。如有必要,请使用 转换为数字类型as.numeric(commandArgs(TRUE)[1])。
回答by Joshua Ulrich
Just a guess, perhaps you need to convert CorrAnsfrom character to numeric, since Value section of ?CommandArgssays:
只是猜测,也许您需要CorrAns从字符转换为数字,因为值部分?CommandArgs说:
A character vector containing the name of the executable and the user-supplied command line arguments.
包含可执行文件名称和用户提供的命令行参数的字符向量。
UPDATE: It could be as easy as:
更新:它可以很简单:
#!/bin/Rscript
args <- commandArgs(TRUE)
(CorrAns = args[1])
(CorrAns = as.numeric(args[1]))
回答by samar
Rscript args.R 10where 10 is the numeric value we want to pass to the R script.
Rscript args.R 10其中 10 是我们要传递给 R 脚本的数值。
print(as.numeric(commandArgs(TRUE)[1])prints out the value which can then be assigned to a variable.
print(as.numeric(commandArgs(TRUE)[1])打印出可以分配给变量的值。
回答by moinudin
Reading the docs, it seems you might need to remove the TRUEfrom the call to commandArgs()as you don't call the script with --args. Either that, or you need to call Rscript Graphs.R --args 10.
阅读文档,似乎您可能需要TRUE从调用中删除,commandArgs()因为您没有使用--args. 要么,要么你需要调用Rscript Graphs.R --args 10.
Usage
commandArgs(trailingOnly = FALSE)Arguments
trailingOnlylogical. Should only arguments after--argsbe returned?
用法
commandArgs(trailingOnly = FALSE)参数
trailingOnly合乎逻辑。应该只--args返回参数吗?

