以下示例顯示了在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))
}
也許你應該用R進行Linux呢? –
對不起,簡單的問題,linux和unix R有什麼區別?我相信我們可以在UNIX上運行R – SHRram
你有什麼嘗試? R應該很好地安裝在unix或linux上,你可以通過命令行用'R'來訪問它。你也可以看看一些出色的guis(我會建議[RStudio](http://www.rstudio.org)作爲一個很好的起點)。最後,運行腳本可以輕鬆完成。通常使用'R CMD BATCH script.R',但有很多備選方案和選項都有詳細記錄。 – Justin