バッチモードでRを動かす

/* シェルスクリプト */
#!/bin/sh
R --vanilla --slave --args < arg.R > arg.txt  0 1 2 a b c
# Rのスクリプト
x<-commandArgs()
print(x)
  • 実行してできた "arg.txt"の中身
 [1] "/Library/Frameworks/R.framework/Resources/bin/exec/x86_64/R"
 [2] "--vanilla"                                                  
 [3] "--slave"                                                    
 [4] "--args"                                                     
 [5] "0"                                                          
 [6] "1"                                                          
 [7] "2"                                                          
 [8] "a"                                                          
 [9] "b"                                                          
[10] "c"                                                          
  • 引数が数字の場合は arg の中から対応する部分を取り出して数字に変換する
# Rのスクリプト
x <- as.numeric(commandArgs()[5:7])
  • --arg 以下(?) 与えた引数のみを取り出すときは trailingOnly = TRUE とすればよい
x<-commandArgs(trailingOnly = TRUE)
# 実行
[1] "0" "1" "2" "a" "b" "c"