I have been defined a bind function ,
b <- function(f,...) function(x) f(x, ...)
so I can do things like (this is a fake example)
d = data.frame(x=c(1,2,1), y=c(10, 20, 5))
ddply(d, ~x, b(transform, y=sum(y)))
instead of
ddply(d, ~x, function (df) { transform(df, y=sum(y)) }
Now, I’m trying to define an operator
'%b%' <- function(x,...) b(x,...)
and try
ddply(d, ~x, transform %b% (z=y*10)))
It doesn’t work. What is the difference ?
When I do
> b(transform, y=y/sum(y))(d)
x y c.1..2..1.
1 1 0.2857143 1
2 2 0.5714286 2
3 1 0.1428571 1
That works, but
> transform %b% (y=y/sum(y))(d)
Error in transform %b% (y = y/sum(y))(d) : object 'y' not found
I understand, there is a ‘capture’ difference, what can I do ?
To make your example work, you need to match the function argument to an existing function, using
match.fun():It will also be safer if you use
match.fun()in your first definition off:Having answered your question, I now have to point out that I don’t understand why you want to do this, since the
plyrfunctions likeddplyas well as the base Rapplyfunctions already do this.So, I would write your original example simply like this:
Edit:
I had another look at your question. You simply made a syntax error in your function definition. This works perfectly fine with an infix operator: