%.%演算子の中身
こんな話があります。
http://stackoverflow.com/questions/21477040/reshape2-multiple-results-of-aggregation-function/21485258?stw=2#21485258
%.%でつなげていけるのはdplyrの関数だけかと思い込んでいたのだがそんなことはない。
helpのdescriptionにもちゃんと書いてあった。
These functions providing an alternative way of calling dplyr (and other data manipulation) functions that you read can from left to right.
%.%の中身をみるとsubstituteで構文木に変換してそれをchain_q関数に渡している。
> `%.%` function (x, y) { chain_q(list(substitute(x), substitute(y)), env = parent.frame()) } <environment: namespace:dplyr>
で、chain_q関数はどうかというとyを分解してxの環境と結合した上で評価するみたいなことをやっている。
その際、xの環境は最初の引数として渡されている。なるほど。
> chain_q function (calls, env = parent.frame()) { if (length(calls) == 0) return() if (length(calls) == 1) return(eval(calls[[1]], env)) e <- new.env(parent = env) e$`__prev` <- eval(calls[[1]], env) for (call in calls[-1]) { new_call <- as.call(c(call[[1]], quote(`__prev`), as.list(call[-1]))) e$`__prev` <- eval(new_call, e) } e$`__prev` } <environment: namespace:dplyr>
xの環境がyの最初の引数として渡されれば良いので下記のようなことができる。
iris %.% lm(formula=Sepal.Width~Species) %.% coef() %.% barplot()