[R] aplpy recursive function on a list

Berend Hasselman bhh at xs4all.nl
Thu Jan 26 19:10:44 CET 2012


On 26-01-2012, at 17:58, Brian Diggs wrote:

> On 1/25/2012 10:09 AM, patzoul wrote:
>> I have 2 series of data a,b and I would like to calculate a new series which
>> is z[t] = z[t-1]*a[t] + b[t] , z[1] = b[1].
>> How can I do that without using a loop?
> 
> A combination of Reduce and Map will work.  Map to stitch together the a and b vectors, Reduce to step along them, allowing for accumulation.
> 
> a <- c(2,4,3,5)
> b <- c(1,3,5,7)
> 
> z <- Reduce(function(zm1, coef) {coef[1] * zm1 + coef[2]},
>            Map(c, a, b),
>            init = b[1], accumulate = TRUE)
> 
> > z
> [1]   1   3  15  50 257

I don't think so.

a <- c(2,4,3,5)
b <- c(1,3,5,7)

z <- rep(0,length(a))
z[1] <- b[1]
for( t in 2:length(a) ) { z[t] <- a[t] * z[t-1] + b[t] }
z

gives

[1]   1   7  26 137

and this agrees with a manual calculation.

You get a vector of length 5 as result. It should be of length 4 with your data.
If you change the Reduce expression to this

u <- Reduce(function(zm1, coef) {coef[1] * zm1 + coef[2]},
           Map(c, a[-1], b[-1]),
           init = b[1], accumulate = TRUE)

then you get the correct result.

> u
[1]   1   7  26 137

Berend



More information about the R-help mailing list