Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive manipulation of vector elements

Tags:

r

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.

like image 540
johannes Avatar asked Dec 13 '22 02:12

johannes


1 Answers

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
like image 68
Joshua Ulrich Avatar answered Jan 07 '23 23:01

Joshua Ulrich