LoginSignup
13
11

More than 5 years have passed since last update.

標準入力で受けたデータをRで加工して標準出力へ渡す

Posted at

データを加工するスクリプトを作ってLinuxのパイプ処理にはさみたいときの話。

標準入力

スクリプトファイルを実行する場合cat hoge.R | R --no-saveのように標準入力を当てることが多い。Rscriptstdinを使えば標準入力をデータ入力に回せる。

標準出力

stdout()を使えばよい。

input.csv
col1,col2,col3
3957,2397,1802
3408,4834,2983
4798,3759,7683
3485,7398,4739

とりあえず正規化してみるスクリプトを噛ます。

process.R
input <- read.csv('stdin')

scaled <- data.frame(cbind(
 scale(input $col1),
 scale(input $col2),
 scale(input $col3)
))

colnames(scaled)<-colnames(input)
write.csv(scaled, stdout())
$ cat input.csv | Rscript process.R 
"","col1","col2","col3"
"1",0.0704684855275962,-1.03924712121725,-0.977681667393651
"2",-0.789247037909078,0.111955258058404,-0.515778657415892
"3",1.38744618172112,-0.395858676172752,1.32244669981989
"4",-0.668667629339635,1.3231505393316,0.171013624989648
13
11
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
13
11