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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With