Both of these functions actually exist in the roxygen
package (see the source code here) from Peter Danenberg (was originally based on Byron Ellis's solution on R-Help):
Curry <- function(FUN,...) {
.orig = list(...);
function(...) do.call(FUN,c(.orig,list(...)))
}
Compose <- function(...) {
fs <- list(...)
function(...) Reduce(function(x, f) f(x),
fs,
...)
}
Note the usage of the Reduce
function, which can be very helpful when trying to do functional programming in R. See ?Reduce for more details (which also covers other functions such as Map
and Filter
).
And your example of Curry (slightly different in this usage):
> library(roxygen)
> p <- Curry(paste, collapse="")
> p(letters[1:10])
[1] "abcdefghij"
Here's an example to show the utility of Compose
(applying three different functions to letters):
> Compose(function(x) x[length(x):1], Curry(paste, collapse=""), toupper)(letters)
[1] "ZYXWVUTSRQPONMLKJIHGFEDCBA"
And your final example would work like this:
> aggregate(df[,"t"], df["l"], Compose(Curry(paste, collapse=""), toupper))
l x
1 1 ABG
2 2 DEFH
3 3 CIJ
Lastly, here's a way to do the same thing with plyr
(could also easily be done with by
or aggregate
as already shown):
> library(plyr)
> ddply(df, .(l), function(df) paste(toupper(df[,"t"]), collapse=""))
l V1
1 1 ABG
2 2 DEFH
3 3 CIJ
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…