johannes
johannes

Reputation: 14413

Recursive manipulation of vector elements

I have a vector a and want to multiply each element recursively with b, without using a loop.

a <- rep(0, 10)
a[1] <- 1
b <- 2

# with a loop
for (i in 2:length(a)) a[i] <- a[i-1] * b

I would be grateful for hints on how to tackle this without using a loop.

Upvotes: 4

Views: 3174

Answers (3)

flodel
flodel

Reputation: 89057

For general recursive series of the form:

y[i] = x[i] + f[1]*y[i-1] + ... + f[p]*y[i-p]

you can use the filter function. In your case, you have x[i] = 0, f[1] = 2 and f[i] = 0 for i > 1. This translates into:

filter(rep(0,10), 2, method="recursive", init=1/2)
# Time Series:
# Start = 1 
# End = 10 
# Frequency = 1 
#  [1]   1   2   4   8  16  32  64 128 256 512

After you learn how to use it, which is not always obvious the first time, filter is very powerful and efficient. But maybe it is overkill for your geometric case here.

Upvotes: 5

flodel
flodel

Reputation: 89057

The exponent function ^ is vectorized, so quite simply:

2^(0:9)
# [1]   1   2   4   8  16  32  64 128 256 512

which you might also want to write

2^seq(from=0, to=9)

For long vectors, I am pretty sure @JoshuaUlrich's method will be much faster, but this one is certainly very compact. You also said you were not particularly concerned about speed.

Upvotes: 3

Joshua Ulrich
Joshua Ulrich

Reputation: 176638

In general, you can't do this without an explicit loop. In this specific case, you can use the implicit loop provided by cumprod:

a <- rep(2, 10)
a[1] <- 1
cumprod(a)
#  [1]   1   2   4   8  16  32  64 128 256 512

Upvotes: 5

Related Questions