Recursive manipulation of vector elements

后端 未结 3 2014
长发绾君心
长发绾君心 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:09

    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.

提交回复
热议问题