使用来自 bash 脚本的参数运行 R 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5247766/
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
Running an R file with arguments from a bash script
提问by lisanne
Possible Duplicate:
How can I read command line parameters from an R script?
可能的重复:
如何从 R 脚本读取命令行参数?
I've got a R script for which I'd like to be able to supply several command-line parameters (rather than hardcode parameter values in the code itself). The script runs on linux.
我有一个 R 脚本,我希望能够为其提供几个命令行参数(而不是代码本身中的硬编码参数值)。该脚本在 linux 上运行。
I can't find out how how to read the R.script on the command line Bash.
我不知道如何在命令行 Bash 上阅读 R.script。
sh file
.sh 文件
cd `dirname args <- commandArgs()
file <- read.csv(args[8],head=TRUE,sep="\t")
annfile <- read.csv(args[9],head=TRUE,sep="\t")
`
/usr/lib64/R/bin/R --vanilla --slave "--args input='' input2='' output=''" file=/home/lvijfhuizen/galaxy_dist/tools/lisanne/partone.R .txt
R file
R文件
#!/bin/bash
rfile=
shift
R --vanilla --slave --args $* < $rfile
exit 0
回答by juba
To source a R script from the command line, you can pipe it into R with <.
要从命令行获取 R 脚本,您可以使用<.
For example, if I create the following test.shbash script :
例如,如果我创建以下test.shbash 脚本:
print(commandArgs(trailingOnly=TRUE))
where test.Ris the following R script in the same directory :
test.R同一目录中的以下 R 脚本在哪里:
$ ./test.sh test.R foo bar 1 2 3
[1] "foo" "bar" "1" "2" "3"
Then running the script with test.Ras first argument and possibly others will give something like this :
然后使用test.R第一个参数运行脚本,其他人可能会给出如下内容:
rfile=
shift
Rscript $rfile $*
EDIT :another way, maybe cleaner, is to use the dedicated Rscriptcommand. Then you can put directly in your bash script something like :
编辑:另一种可能更简洁的方法是使用专用Rscript命令。然后你可以直接在你的 bash 脚本中输入:
which should give the same results.
这应该给出相同的结果。

