Recursive manipulation of vector elements

后端 未结 3 2013
长发绾君心
长发绾君心 2021-01-13 16:45

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 <         


        
3条回答
  •  醉酒成梦
    2021-01-13 17:28

    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
    

提交回复
热议问题