[R] Composing a sequence of functions dynammically

Saptarshi Guha saptarshi.guha at gmail.com
Fri Dec 25 23:16:51 CET 2009


Hello,
I would like to compose a series of functions each taking one
argument. Let us assume the values returned by the functions are
contained within the domains.

So
b<-function(r) r[-1]

compose("b","b")
b(b(x))

This is my solution, is there something succinct ?
Regards
Saptarshi

compose <- function(...){
  fns0 <- list(...)
  g <- function(x) {}
  compose2 <- function(fns){
    if(length(fns)==1){
      as.call(list(as.name(fns[[1]]),quote(x)))
    }else{
      as.call(  list( as.name(fns[[ length(fns) ]]),  compose2(
fns[1:(length(fns)-1)])))
    }
  }
  body <- compose2(fns0)
  body(g,envir=parent.frame()) <- body
}

b <- function(r) r[-1]
j=compose("b","b")




More information about the R-help mailing list