LoginSignup
11
11

More than 5 years have passed since last update.

R の NSE を駆使して pipeR ワールドを作る #rstatsj

Last updated at Posted at 2014-10-28

R 界隈で NSE の話題が持ち上がっているようで。

このタイミングで、NSE を使って pipeR ワールドを作るという超どうでもいい話をします。

pipeR を知らないという方はこちらをご一読ください。

さて、pipeR でフツーにコードを書くと、こんなコードが出来上がりますね。

R
library(pipeR)

cars %>>%
  (~ plot(dist ~ speed, data=.)) %>>%
  (lm(dist ~ speed, data=.)) %>>%
  abline(col="red")

pipeR の最大の弱点とは何でしょうか?
そう、それは可読せ %>>% 演算子を書くのが面倒くさいということですね。

そこで、NSE を使って次のような関数を用意します。

R
pipeR_world <- function(expr) {
  require(pipeR)
  expr <- substitute(expr)
  n <- length(expr)
  pipeExpr <- ""
  for(i in seq_len(n)) {
    e <- deparse(expr[i])
    if(length(e) == 1) {
      str <- substr(e, 1, nchar(e)-2)
      pipeExpr <- paste(pipeExpr, str)
      if(i != n) {
        pipeExpr <- paste(pipeExpr, "%>>%")
      }
    }
  }
  eval(parse(text=pipeExpr), envir = parent.frame())
}

この関数を使えば、先ほどのコードは次のように書くことができます。

R
pipeR_world({

  cars
  (~ plot(dist ~ speed, data=.))
  (lm(dist ~ speed, data=.))
  abline(col="red")

})

なんと、パイプ %>>% を全く書かなくても済むようになりました!
pipeR_world() 関数によって、pipeR の世界が作られたのです。

この世界では、人々はパイプから解放されます。
pipeR には、本当はパイプなんて必要なかったんやー。

この世界でプログラミングすると、普通の R プログラミングと全く異なる次元の体験ができるのでお勧めです。
みなさんもぜひ pipeR_world の一員になりましょう!

enjoy!

追記

本家へ取り込まれました

11
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
11
11