[R] aplpy recursive function on a list

Brian Diggs diggsb at ohsu.edu
Thu Jan 26 17:58:29 CET 2012


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


> --
> View this message in context: http://r.789695.n4.nabble.com/aplpy-recursive-function-on-a-list-tp4328017p4328017.html
> Sent from the R help mailing list archive at Nabble.com.
>


-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University



More information about the R-help mailing list