Rik
Rik

Reputation: 1987

Recursion on apply

I tried performing the following recursion:y[i]=y[i-1]+a[i] and I tried:

   apply(c(2:10),2,function(x) y[x]=y[x-1]+a[x])

But it did not work. Is there some other way to do this without a loop?

Upvotes: 1

Views: 71

Answers (2)

Jthorpe
Jthorpe

Reputation: 10167

This is faster:

c(0,cumsum(a[c(-1,-length(a))])) + 1

or equivalently:

c(0,cumsum(a[seq(2,10)])) + 1

Upvotes: 3

LyzandeR
LyzandeR

Reputation: 37879

You need sapply on this occasion and also the <<- operator if you want to assign values to y inside the sapply. The following works:

Example data:

y    <- vector() #initiate a vector (can also simply do y <- 1 )
y[1] <- 1        #I suppose the first value will be provided
a    <- 20:30    #some random data for a

Solution:

#sapply works for vectors i.e. for your 2:10, c() is unnecessary btw
#<<- operator modifies the y vector outside the sapply according to the formula 
> sapply(c(2:10), function(x) {y[x] <<- y[x-1] + a[x]} )
[1]  22  44  67  91 116 142 169 197 226

#y looks like this after the assignments 
> y
 [1]   1  22  44  67  91 116 142 169 197 226

Upvotes: 2

Related Questions