4

Possible Duplicate:
R Pipelining functions

I find R syntax very unwieldy compared to F#:

In R - Instead of:

plot(exp(cumsum(returns)))

I would love to do

returns |> cumsum |> exp |> plot

Is there a way to overload an operator in R to achieve a similar effect?

thanks

Community
  • 1
  • 1
nxstock-trader
  • 223
  • 2
  • 6

2 Answers2

16

sure, why not,

`%|>%` = function(x, y) y(x)
1:10 %|>% cumsum %|>% plot
baptiste
  • 75,767
  • 19
  • 198
  • 294
5

Stolen from the Reduce help page:

Funcall <- function(f, ...) f(...)
Reduce(Funcall, list(plot, exp, cumsum), 1:10, right = TRUE)
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • The advantage of this approach is that it's easier to read (at least for users of R, Matlab, scipy, etc) and overall easier to "drop into" existing R functions designed for recursive and repetitive operations (e.g. `*apply`). THen again, I'm the wiseguy who overloaded `!` as seen in http://stackoverflow.com/questions/13195165/r-unary-operator-overload-risks – Carl Witthoft Dec 31 '12 at 13:52
  • can anyone recommend a way to come up with a shorter operator than %|>% is? – nxstock-trader Dec 31 '12 at 18:49
  • It's difficult to imagine a shorter version than babtiste's given the manner in which functions get defined in R. And given the "closed" nature of this question, you should be posting comments in answers to an open question. – IRTFM Dec 31 '12 at 18:54
  • @nxstock-trader You could define any `%[char]%` you wanted, or follow my link to an overload for `![char]` – Carl Witthoft Dec 31 '12 at 21:24