I would like to create a function, "compose" in R which will compose an arbitrary number of functions given as arguments.
So far, I have accomplished this by defining a function "of" that composes two arguments and then Reducing this:
of <- function(f,g) function(x) f(g(x))
id <- function(x) x
compose <- function(...) {
argms = c(...)
Reduce(of,argms,id)
}
This seems to work fine, but since I'm learning R, I thought I'd try to write it in an explicit recursive style, i.e. forgoing the use of Reduce, iow the sort of thing that you would do in Scheme like this:
(define (compose . args)
(if (null? args) identity
((car args) (apply compose (cdr args)))))
I have come up against a number of obstacles, the major one at the moment seems to be that the first element of the arguments is not getting recognized as a function. My weak attempt so far:
comp <- function(...) {
argms <- list(...)
len <- length(argms)
if(len==0) { return(id) }
else {
(argms[1])(do.call(comp,argms[2:len]))
}
}
Spits out: Error in comp(sin, cos, tan) : attempt to apply non-function
There must be some way to do this which eludes me. Any suggestions?