向 R CMD BATCH 和 Rscript 傳遞命令列引數

Jesse John 2023年1月30日
  1. 使用 commandArgs() 函式檢索 R 中的引數
  2. 使用 R CMD BATCH 命令重定向 R 中的輸出
  3. 在 R 中建立指令碼並執行命令
  4. 將命令列引數傳遞給 R 中的 R CMD BATCH 命令
  5. 將命令列引數傳遞給 R 中的 Rscript
向 R CMD BATCH 和 Rscript 傳遞命令列引數

當使用命令列執行 R 指令碼檔案時,我們可能希望傳遞引數並將輸出儲存在檔案中。本文使用 R CMD BATCH 命令和 Rscript 前端演示了這些技術。

我們將從兩種方法共有的一些細節開始。

使用 commandArgs() 函式檢索 R 中的引數

應使用 commandArgs() 函式檢索在命令列上傳遞的引數。我們將使用引數 trailingOnly=TRUE

該函式返回一個字元向量。

使用 R CMD BATCH 命令重定向 R 中的輸出

R CMD BATCH 命令將輸出重定向到 .Rout 檔案。該檔案包含輸入命令、結果和錯誤訊息。

使用 Rscript 前端,我們必須使用適當的 shell/終端命令來重定向輸出。對於幾個終端,它是 > 檔名

我們可以在檔案開頭使用 options(echo=TRUE) 重定向輸入。錯誤訊息不會被重定向。

將輸出重定向到檔案時必須小心。如果檔案不存在,則會建立該檔案,否則將被覆蓋。

在 R 中建立指令碼並執行命令

要檢視每種方法的工作原理,請執行以下操作。

  • 使用給定的 R 程式碼建立一個檔案,並將其以副檔名 .R 儲存在目錄中以執行 R 命令。
  • 在包含指令碼檔案的目錄中開啟 shell。
  • 將給定的檔名替換為檔名後執行相應的命令。
  • 在這些示例指令碼中,第一個引數是 hobby,第二個引數是 years

將命令列引數傳遞給 R 中的 R CMD BATCH 命令

語法如下。

R CMD BATCH options "--args userargument1 userargument2" script_filename.R

引數不能包含空格。確切的引用將取決於使用的 shell。

--vanilla 選項結合了幾個 R 選項。

R 檔案的示例程式碼:

# Create 5 values in a sequence.
x = seq(from=0, to=20, by=5)
print(x)

# Get the arguments as a character vector.
myargs = commandArgs(trailingOnly=TRUE)
myargs

# The first argument is the text for hobby.
hobby = myargs[1]
hobby

# The second argument is the number of years of practice.
years = as.numeric(myargs[2])
years

命令:

R CMD BATCH --vanilla "--args Golf 8" script_filename.R

在輸入檔案的同一目錄中建立一個與輸入檔案同名、副檔名為 .Rout 的輸出檔案。

將命令列引數傳遞給 R 中的 Rscript

Rscript 是 R 的指令碼前端。

引數可能包含空格。這樣的引數需要用引號引起來。

語法如下。

Rscript script_filename.R 'user argument 1' userargument2 > rscript_output_file_name.txt

R 檔案的示例程式碼:

# To print the command and its result in the output.
options(echo=TRUE)

# five random values from the standard normal distribution
x = rnorm(5)
print(x)

# Get the arguments as a character vector.
myargs = commandArgs(trailingOnly=TRUE)
myargs

# The first argument is the text for hobby.
hobby = myargs[1]
hobby

# The second argument is the number of years of practice.
years = as.numeric(myargs[2])
years

命令:

Rscript script_filename.R 'Playing Guitar' 3 > rscript_output_file_name.txt

輸出檔案被建立。它有輸入和輸出,但沒有錯誤訊息。

參考和幫助

請參閱手冊的附錄 B,呼叫 R:R 簡介

此外,請參閱 R 的 commandArgs() 函式和 Rscript 工具的文件。

作者: Jesse John
Jesse John avatar Jesse John avatar

Jesse is passionate about data analysis and visualization. He uses the R statistical programming language for all aspects of his work.