Let's assume I have the closure
F <- function(a, b) { function(x) { a*x^b } }
and I want to create a sum G of F-functions
G(x, y, z) = F_1(x) + F_2(y) + F_3(z)
that depends on several variables (not just x). However, F_2 should not depend on x for example.
For start, I would use a function that adds together a list of functions:
addFunctions <- function(x, l) { # x variable # l list of functions sum(sapply(l, function(f) f(x))) }
I start by defining the F-functions and
F_1 <- F(1, 2) F_2 <- F(3, 4) F_3 <- F(4, 5)
G <- function(x) {addFunctions(x, list(F_1, F_2, F_3))}
However, this would only give me a function G of one variable x.
Why wouldn't I just define the sum directly? Well, because the case I really have is much more complicated and the number of independent variables may vary.
Any suggestions?