Search code examples
rsum

How to write and calculate Sum/ Product (of a function) in R


Assuming that I have a function, let's say f(x).

How can I write the product or sum of this function for given limits in x.

For instance product of f for x=1 until x=5 f(1)*f(2)*f(3)*f(4)*f(5)

Additionally I need to figure this out for sums/double sums. Consider f(x,y) and the sum while x runs from 1 to 3 and y runs from 0 to x-1. If written in mathematica, it would be this: Sum[f[x, y], {x, 1, 3}, {y, 0, x - 1}] and the output would be this f[1, 0] + f[2, 0] + f[2, 1] + f[3, 0] + f[3, 1] + f[3, 2]

f is not defined for simplicity.

EDIT: example as requested:

f <- function (x,y) { 
x + 2*y 
} 

Calculate sum where x runs from 1 to 3 and y runs from 0 to x-1. (this is equal to 22 btw)


Solution

  • You can do this:

    f <- function (x,y) { 
      x + 2*y 
    }
    )
    
    #calculate f for all combinations
    tmp <- outer(1:3, 0:2, f)
    
    #discard undesired combinations and sum
    sum(tmp[lower.tri(tmp, diag = TRUE)])
    #[1] 22
    

    Alternatively you can use a loop to create the desired combinations only. This is much slower:

    inds <- lapply(1:3, function(x) data.frame(x = x, y = 0:(x-1)))
    inds <- do.call(rbind, inds)
    sum(do.call(f, inds))
    #[1] 22