下面的示例显示了在 shell 脚本中运行 R 代码的两种方法。如果脚本通过 source() 函数加载到交互式 R 会话,这两个示例也将定义函数而不执行它们。
第一个示例允许您像向任何其他 shell 脚本一样提供参数,但不会将额外的 R 选项传递给 R(因为 Rscript 将“--args”作为参数之一提供给 R)。
第二个示例允许您提供额外的 R 选项,但会生成(无害的)警告消息,除非您将“--args”作为脚本参数之一。除非您有特殊要求,否则最好避免使用此版本。
原型-Rscript.r
#!/usr/bin/env Rscript
# Prototype R script for use at command line in Linux, Mac OS X, UNIX
# References:
# Manual "A Introduction to R", available via help.start() from the R Console
# Appendix "B.1 Invoking R from the command line" in "A Inroduction to R",
showArguments <- function(argv) {
print(argv)
0
}
if ( ! interactive() ) {
# set some error return codes
SCRIPT_ERROR <- 10 # see documentation for quit()
SCRIPT_ARG_ERROR <- SCRIPT_ERROR + 1
# Define ARGV as script path concatenated to script arguments
ARGV <- commandArgs(FALSE) # start with all the arguments given to R
scriptPath <- sub("^--file=", "", grep("^--file=", ARGV, value=TRUE)) [[1]]
ARGV <- c(scriptPath, commandArgs(TRUE))
if (length(ARGV) < 2) {
cat(file=stderr(), sep="",
"Usage: ", ARGV[[1]], " [ options ] item ...\n",
" Do something with item\n",
" See script for details\n")
quit(save="no", status=SCRIPT_ARG_ERROR)
}
quit(save="no", status=showArguments(ARGV))
}
原型-shellscript.r
#!/usr/bin/env R --slave --vanilla --quiet -f
# Prototype R script for use at command line in Linux, Mac OS X, UNIX
# References:
# Manual "A Introduction to R", available via help.start() from the R Console
# Appendix "B.1 Invoking R from the command line" in "A Inroduction to R",
showArguments <- function(argv) {
print(argv)
0
}
if ( ! interactive() ) {
# set some error return codes
SCRIPT_ERROR <- 10 # see documentation for quit()
SCRIPT_ARG_ERROR <- SCRIPT_ERROR + 1
# Define ARGV as the arguments given to this script (after argument “-f”)
ARGV <- commandArgs(FALSE) # start with all the arguments given to R
ARGV <- ARGV[(grep("-f", ARGV) [[1]] + 1):length(ARGV)]
if ( any(grepl("--args", ARGV) )) { # remove arguments intended only for R
ARGV <- c(ARGV[[1]], commandArgs(TRUE))
}
if (length(ARGV) < 2) {
cat(file=stderr(), sep="",
"Usage: ", ARGV[[1]], " [ R_options ] --args [ options ] item ...\n",
" Do something with item\n",
" See script for details\n")
quit(save="no", status=SCRIPT_ARG_ERROR)
}
quit(save="no", status=showArguments(ARGV))
}