LoginSignup
7
10

More than 5 years have passed since last update.

コマンドラインでRを実行するRioの紹介

Posted at

はじめに

  • コマンドラインではじめるデータサイエンスを読み始めて気になったツール。
  • Rの関数などを気軽にRを起動せずとも、気軽にコマンドラインからRを操作できるツール
  • 中身は、jeroenjanssensのGithubページを読めば分かるが、1つのシェルスクリプト。
    • csvファイルを指定して、それをdata.frameのdfオブジェクトにロードして、Rの文法で操作できるということをしてる。シンプルだけど、便利そう。

インストール

  • git clone してから、PATHの通っている場所にRioを置くだけ
  • Rがインストールされてないと実行時にエラーが吐かれます
$ git clone https://github.com/jeroenjanssens/data-science-at-the-command-line.git
$ sudo mv data-science-at-the-command-line/tools/Rio /usr/local/bin/

確認してみる。ggplot / dplyr / tidyrをインストールしてるのが前提みたいです。

$ Rio -h
Rio: Load CSV from stdin into R as a data.frame, execute given commands, and get the output as CSV on stdout

usage: Rio OPTIONS

OPTIONS:
   -d      Delimiter
   -e      Commands to execute
   -f      Single command to execute on data.frame
   -h      Show this message
   -g      Import ggplot2
   -n      CSV has no header
   -r      Import dplyr and tidyr
   -s      Import sqldf
   -b      Use same settings as used for book Data Science at the Command Line
   -v      Verbose

実行

iris.csvに対して、ある列の平均を見る

$ head iris.csv -n 3
,Sepal.Length,Sepal.Width,Petal.Length,Petal.Width,Species
1,5.1,3.5,1.4,0.2,setosa
2,4.9,3,1.4,0.2,setosa

-e オプションでRの文法で実行

$ Rio -e 'mean(df$Sepal.Length)' < iris.csv
5.843333
$ Rio -e 'summary(df$Sepal.Length)' < iris.csv
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  4.300   5.100   5.800   5.843   6.400   7.900

-f オプションでRのある関数を実行

相関行列を計算

$ cut -d, -f 2,3 iris.csv | Rio -f cor
"Sepal.Length","Sepal.Width"
1,-0.117569784133002
-0.117569784133002,1

-g オプションでggplotを実行

例えば、Sepal.Lengthの密度分布を描くのは下記。"g"ってのがggplot()を呼び出す。ggplotの結果は、pngファイルに書き出せば表示できるみたい。

$ Rio -ge 'g+geom_histogram(aes(x=Sepal.Length))' < iris.csv > result.png

おわりに

  • コマンドラインからRをちょっと試して確認したいってのはニーズがあるので、そういうときに便利そう。Rファイルをいちいち作らなくていい。
  • dplyrも呼び出せるので、パイプ演算子で、データ前処理して、可視化まではすぐにできそう。可視化結果はどっかのWebサーバが起動しているところにpngファイルを置くとか。
  • Rio自体をもっと汎用的にしていくのに期待。

参考

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10