在Unix中使用参数执行R脚本
问题描述:
在Unix脚本中,是否有任何方法可以运行R文件,但在Unix脚本中有参数?在Unix中使用参数执行R脚本
我知道,在系统运行R上的文件,你需要输入“R -f‘文件’,但你R中需要这样你将需要在Unix,而不是输入这个代码是什么:
“R -f ”文件“ ARG1 ARG2”
答
下面是一个例子,test.R将该代码:。
#!/usr/bin/env Rscript
# make this script executable by doing 'chmod +x test.R'
help = cat(
"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Help text here
Arguments in this order:
1) firstarg
2) secondarg
3) thirdarg
4) fourtharg
./test.R firstarg secondarg thirdarg fourtharg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\n\n")
# Read options from command line
args = commandArgs(trailingOnly = TRUE)
if(is.element("--help", args) | is.element("-h", args) | is.element("-help", args) | is.element("--h", args)){
cat(help,sep="\n")
stop("\nHelp requested.")
}
print(args)
做chmod +x test.R
它使用./test.R a b c d
然后调用它会打印:[1] "a" "b" "c" "d"
。
您可以通过执行args[1]
访问每个参数以获得a
和args[4]
以获得d
。
答
使用Rscript的建议似乎很有用,但可能不是要求提供的内容。也可以从命令行使用获取来源的输入文件启动R. R解释器也可以在该模式下访问commandArgs。这是在我的用户目录下的最小“ptest.R”的文件,这也是我的默认工作目录:
ca <- commandArgs()
print(ca)
从UNIX命令行我可以这样做:
$ r -f ~/ptest.r --args "test of args"
和R打开,显示通常的启动消息并宣布由.Rprofile
加载的包然后:
> ca <- commandArgs()
> print(ca)
[1] "/Library/Frameworks/R.framework/Resources/bin/exec/R"
[2] "-f"
[3] "/Users/davidwinsemius/ptest.r"
[4] "--args"
[5] "test of args"
>
>
然后退出。
我现在编辑了这些问题。 – erver