BioBroo
BioBroo

Reputation: 683

How to add functions in R

I am trying to sum the functions in a list to create a new function. This is easy for a small number of functions. Here is an example:

f <- function(x){x}
g <- function(x){x+1}

Now we sum f and g.

fg <- function(x){f(x) + g(x)}

But if I have 100 functions that I want to sum, this method becomes clumsy. Is there a way to create a function like fg above automatically from a list?

Upvotes: 2

Views: 120

Answers (3)

akrun
akrun

Reputation: 887501

You may try:

 fun1 <- function(i,a) {
                eval(substitute(function(x, a) {x+i*a}, list(i=i)))}

n <- 0:3
lst <- lapply(n, fun1)
rowSums(sapply(lst, function(f) f(12:14, 3)))
#[1] 66 70 74

Upvotes: 0

Roland
Roland

Reputation: 132864

I prefer Reduce:

f <- function(x){x}
g <- function(x){x+1}
h <- function(x){x*2}

funs<-list(f,g,h)

x <- 1:3

Reduce("+", lapply(funs, function(f, y) f(y), y=x))
#[1]  5  9 13

Of course, the return values of all functions must have the same length.

Upvotes: 4

MrFlick
MrFlick

Reputation: 206401

You could use sapply to loop over the functions and apply then

f <- function(x){x}
g <- function(x){x+1}
h <- function(x){x*2}

funs<-list(f,g,h)

x <- 2
rowSums(matrix(sapply(funs, function(f, z) f(z), z=x), nrow=length(x)))
# [1] 9

I use the matrix and rowSums functions just in case you want to be able to call it when x is a vector of values as well

x <- 1:3
rowSums(matrix(sapply(funs, function(f, z) f(z), z=x), nrow=length(x)))
# [1]  5  9 13

You can make it cleaner by making a helper function

getfunsum <- function(funs) {
    force(funs)
    function(x) {
        rowSums(matrix(sapply(funs, function(f, z) f(z), z=x), nrow=length(x)))
    }
}
fgh <- getfunsum(funs)
fgh(1:3)
# [1]  5  9 13

Upvotes: 1

Related Questions