行の先頭に%>%を持ってくるには

magrittrの人がこんなつぶやきをしていました。

ちょっと話はずれますが、そういえば、みんなのRに、こういう改行の仕方をするとだめだよ、という話が載ってました。どこがダメかわかりますか?

if(FALSE)
{
  print("unhappy")
}
else
{
  print("happy")
}

これは、if文はelseなしでも完結するので、if(FALSE){...}までで解釈されてしまいます。分かりやすく改行を入れると、こんな感じ。

if(FALSE)
{
  print("unhappy")
}

else
#> Error: unexpected 'else' in "else"

{
  print("happy")
}
[1] "happy"

ただ、これを関数の中で使うと問題なくて混乱しました。

f <- function()
{
  if(FALSE)
  {
    print("unhappy")
  }
  else
  {
    print("happy")
  }
}

f()
#> [1] "happy"

よく分からないんですが、function()の中に入れたり()でくくったりすると、そのコードブロックの最後まで読んでから解釈してくれるからっぽいです。?Parenでヘルプを見ると、こんな風に書いてありました。

Effectively, ( is semantically equivalent to the identity function(x) x, whereas { is slightly more interesting, see examples.

For (, the result of evaluating the argument. This has visibility set, so will auto-print if used at top-level.
For {, the result of the last expression evaluated. This has the visibility of the last evaluation.

その「example」として載っているのはこんなコードです。

(2+3)
#> [1] 5
{2+3; 4+5}
#> [1] 9

(invisible(2+3))
#> [1] 5
{invisible(2+3)}
# (何も出力されない)

()は中身をまとめて評価して結果の値を返しますが、{}は順々に評価していって最後の値だけを返すみたいです。

上の話のように演算子を頭に持ってくるのは()しか無理でした。

{
  ggplot(iris, aes(Species))
    + geom_bar()
}
Error in +geom_bar() : invalid argument to unary operator

(
  ggplot(iris, aes(Species))
    + geom_bar()
)

うーん、奥が深い。来年1/24発売のR言語徹底解説を読んで勉強しなおそっと。