Run R script from command line on Ubuntu


Outline
  1. 1. Install R on Ubuntu
  2. 2. Run R script from command line
    1. 2.1. 方法一:use Rscipt
    2. 2.2. 方法二:第一行加入 #!/usr/bin/Rscript 如下範例程式:
    3. 2.3. If you get ^M Problem
  3. 3. Read Command line Argument
  4. 4. Reference

目的:希望能透過 cmd 的方式執行 ./script.r 的檔案,並且讀進 Arguments

Install R on Ubuntu

1
2
3
4
$ sudo apt-get update
$ sudo apt-get install r-base
# installing packages
$ sudo apt-get install r-base-dev

Run R script from command line

方法一:use Rscipt

方法二:第一行加入 #!/usr/bin/Rscript 如下範例程式:

  • Sample code test.r:
1
2
#!/usr/bin/Rscript
print("HelloR")
  • Reminding: You can use $ which Rscript to search your path to Rscript.
1
2
$ which Rscript
/usr/bin/Rscript
  • Run sample code test.r from command line:
1
2
3
4
# 方法一執行方式
$ Rscipt test.r
# 方法二執行方式
$ ./test.r

If you get ^M Problem

1
2
$ ./test.r
zsh: ./test.r: bad interpreter: /usr/bin/Rscript^M: 沒有此一檔案或目錄

This is an encoding problem at the end of line, your can use Line endings setting of Sublime: View > Line Endings > Unix

▲ Figure: Line endings setting of Sublime

Read Command line Argument

  • Sample code test.r:
1
2
3
#!/usr/bin/Rscript
args<-commandArgs(TRUE)
print(args[1])
  • Run sample code test.r from command line:
1
2
$ ./test.r 1 2 3 4
[1] "1"
  • Reminding: Arguments list start from index 1.

Reference