Onyambu
Onyambu

Reputation: 79228

Unlisting a list of functions in R

I have a list which at least one of the elements is a function: I would like to unlist it. All the functions are somehow related and would like to obtain one function that takes in all the parameters used and outputs the specified results:

f=c(a=function(x,y)x+y+2*x^2,b=function(m)m*exp(m),d=function(x,m)x^2+2*x*m)
f
$a
function (x, y) 
x + y + 2*x^2

$b
function (m) 
m * exp(m)

$d
function (x, m) 
x^2 + 2 * x * m

Expected output:

g = function(x) c(x[1] + x[2] + 2*x[1]^2, x[3] * exp(x[3]), x[1]^2+2*x[1]*x[3])

Can be a function of anything not necessarily x. If Possible, Base R solution is preferred: (will take other packages too)

My trial:

`unlist(f)` :this fails
f=sub(",.*","",deparse(f)[-1]);f[length(f)]=sub(")$","",f[length(f)])
 f
[1] "x + y"           "m * exp(m)"      "x^2 + 2 * x * m"

Thank you

Upvotes: 0

Views: 199

Answers (1)

Roland
Roland

Reputation: 132706

Your problem is not very well described, but you could do something like this:

f=c(a=function(x,y)x+y+2*x^2,b=function(m)m*exp(m),d=function(x,m)x^2+2*x*m)
x <- setNames(1:3, c("x", "y", "m"))

foo <- function(x, f) {
  #add ... to avoid unused arguments error
  f <- lapply(f, function(fun) {
    if ("..." %in% names(formals(fun))) return(fun)
      else formals(fun) <- c(formals(fun), alist(... =))
    fun
  })
  x <- as.list(x)
  #call the functions
  vapply(f, function(fun) do.call(fun, x), FUN.VALUE =  numeric(1))
}

foo(x, f)
#      a        b        d 
#5.00000 60.25661  7.00000 

Upvotes: 1

Related Questions