5

I need to write a cumulative summation function in R but I've been hitting a brick wall. The function has the following structure:

a*x1
a*x2 + a^2*x1
a*x3 + a^2*x2 + a^3*x1
a*x4 + a^2*x3 + a^3*x2 + a^4*x1

And so on. cumsum doesn't seem to work for this type of function. Is there any way this could be implemented in R?

3
  • 2
    Can you provide some sample input and the expected result?
    – Dason
    Jul 19, 2012 at 1:20
  • I am looking for something like 1) .5*1=.5 (2) .5*2+.25*1=1.25 (3) .5*3+.25*2+.125*1 = 2.125, and so on. Jul 19, 2012 at 1:29
  • You should add that to the question instead of having it as a comment.
    – Dason
    Jul 19, 2012 at 1:34

1 Answer 1

10

Since your recursion is

u[n+1] = a * ( x[n+1] + u[n] )

i.e.,

u[n+1]/a = x[n+1] + a * u[n]/a,

you can use filter:

x <- 1:5
a <- 2
a*filter(1:5, a, method="recursive")

# Compare with the expected values
a*x[1]
a*x[2] + a^2*x[1]
a*x[3] + a^2*x[2] + a^3*x[1]
a*x[4] + a^2*x[3] + a^3*x[2] + a^4*x[1]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.