Search code examples
rqueuecircular-buffer

R circular array/vector


Does a R package exist which implements a circular array or vector in the sense of FIFO?

Say we have this array:

2 4 7 1

When inserting a new observation(say 3) at position 1, I want the n-th element to be replaced with the n-1st element:

3 2 4 7

Solution

  • You could try c() and cut off the length of the result.

    x <- c(2, 4, 7, 1)
    c(3, x)[1:length(x)]
    # [1] 3 2 4 7
    

    This method does not make any copies of x

    tracemem(x)
    # [1] "<0x3cb5998>"
    c(3, x)[1:length(x)]
    # [1] 3 2 4 7
    untracemem(x)
    

    The source code for append() looks like it might have some useful methods to try out as well.

    append
    # function (x, values, after = length(x)) 
    # {
    #     lengx <- length(x)
    #     if (!after) 
    #         c(values, x)
    #     else if (after >= lengx) 
    #         c(x, values)
    #     else c(x[1L:after], values, x[(after + 1L):lengx])
    # }
    # <bytecode: 0x31ac490>
    # <environment: namespace:base>