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 <
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.
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.
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