Recursive manipulation of vector elements

后端 未结 3 1984
长发绾君心
长发绾君心 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.

    0 讨论(0)
  • 2021-01-13 17:16

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题