Werden wir Helden für einen Tag

Home | About | Archive

讓 R 在 Shell 中行

Posted on Nov 9, 2010 by Chung-hong Chan

工作地方自行變成 Linux 機後,可以研習的東西多了很多。
以前寫落不少小程序,是用 R 來生產一些每月都要 Run 一次的 Report 。用到 R2HTML 這個套件。
以前都是用 emacs 中的 ESS 來行 R Script ,都覺得煩。
最後想試下在 Shell 中行,一輸入搞掂那種。
經過訪查之後,係可以這樣:

#!/usr/bin/env Rscript
# chew that < -
hello <- 1+1
hello

秘密是在第一句的 shebang 。將以上東西 save 成一個 test.R ,再將它轉成 executable (chmod +x test.R) 及在 shell 執行。 (./test.R)

chainsaw@revo:~$ ./test.R
[1] 2

甚至可以有 command argument ,可用到 R 的 commandArgs() function 。

#!/usr/bin/env Rscript
# chew that < -
args <- commandArgs()
args

例如在 shell 輸入

chainsaw@revo:~$ ./test.R 1 2
[1] "/usr/lib/R/bin/exec/R" "--slave" "--no-restore"
[4] "--file=./test.R" "--args" "1"
[7] "2"

1 和 2 就會是 args 的第六及第七位,但需注意是以 String 儲存,而非 numeric 。

#!/usr/bin/env Rscript                                                                                            
# chew that < -                                                                                                    
args <- commandArgs()
mynum <- as.numeric(args[6])
hello <- 1+mynum
hello

當輸入 ./test.R 及 argument ,結果是

chainsaw@revo:~$ ./test.R 1
[1] 2
chainsaw@revo:~$ ./test.R 11
[1] 12


Powered by Jekyll and profdr theme