r-statistics-fanの日記

統計好き人間の覚書のようなもの

#dplyr #magrittr のお勉強

##dplyr
##magrittr

http://d.hatena.ne.jp/teramonagi/20140814/1408024760
http://d.hatena.ne.jp/teramonagi/20140403/1396529027
http://rpubs.com/teramonagi/1112
http://meme.biology.tohoku.ac.jp/students/iwasaki/rstats/tidyr.html
http://meme.biology.tohoku.ac.jp/students/iwasaki/rstats/plyr.html#module-dplyr
https://github.com/smbache/magrittr

にて、magrittrが勧められていた。
諸先輩方が勧めるというのは、なにか理由があるのだろう。

前から気になっていたので、使ってみる。

勉強のため上記のサイトのコードをなぞる。
library(dplyr)
library(magrittr)
iris %>%
mutate(Width=Sepal.Width+Petal.Width) %>%
group_by(Species) %>%
summarize(AverageWidth=mean(Width)) %>%
use_series(AverageWidth) %>%
divide_by(3) %>%
max

なるほど。良く分からんが、次々結果を受け渡して、データフレームの
処理ができるらしい。慣れれば、見通しが良さそう。
たしかに、統計処理の際、ある変数と別の変数で値を作成して、
そこから、二値化したり、診断基準のスコアで分類したり、
ずらずらと並べることが多い。
しかも、従来の処理より高速だという。
オラ、なんだか便利という気がしてきたぞ

iris %>% #これは、左の値を右の関数に渡す。つまり、mutateに渡す
mutate(Width=Sepal.Width+Petal.Width) %>% #mutateは左から右へ逐次的に処理する。tranformは一気に元データから。
#こうして出来た新たな変数Widthが入ったデータを更に右に渡す.
group_by(Species) %>% #グループごとに区切って次の処理に渡す。
summarize(AverageWidth=mean(Width)) %>% #列に対する関数をグループごとに適用して1行にしたものを rbind() してまとめる:
use_series(AverageWidth) %>% #’$’と同じ。
divide_by(3) %>% #’/’と同じ。3で割る
max #最大値

これまでの自分ならこうしてた。

iris$Width <- iris$Sepal.Width + iris$Petal.Width
AverageWidth <- by (iris$Width, iris$Species, mean)
max(AverageWidth / 3)

更にはpipeRなるものもあるらしい
http://d.hatena.ne.jp/dichika/20140818

library(pipeR)
library(dplyr)
library(magrittr)
Pipe(iris)$mutate(Width=Sepal.Width+Petal.Width)$group_by(Species)$summarize(AverageWidth=mean(Width))$select(AverageWidth)$divide_by(3)$max()

途中経過で処理をしたいなら
http://d.hatena.ne.jp/dichika/20140731
http://d.hatena.ne.jp/dichika/20140701

しかし%T>%が無いと言われる。
インストールが上手く行っていないのかとも思い、
Rのバージョンを変えたりしたがダメ。
結局

library(devtools)
devtools::install_github("smbache/magrittr")
install_github("teramonagi/magrittr@work")

にてインストールした所動くようになった。

#途中でplotしたり途中のデータフレームを保存する
iris %>%
mutate(Width=Sepal.Width+Petal.Width) %>%
group_by(Species) %>%
summarize(AverageWidth=mean(Width)) %->% res1 %>%
use_series(AverageWidth) %>%
divide_by(3) %T>% plot(.) %>%
max -> res2
res1
res2

できた。
今後積極的に使用していきたい。
%T>%だけで2時間位悩んだよorz