Search code examples
rlistdeque

Generating a list with fixed length


I need to generate a fixed-length list so that when the length is exceeded, the earliest item entered the list is dropped. This can be achieved by using deque (list-like container with fast appends and pops on either end) in Python.

I was wondering whether there is an R equivalent of python's deque ?

I know about dequer and rstackdeque libraries but none of them provide a fixed length queue.

Thanks in advance.


Solution

  • Not sure this is the best way to do it but based on the comment by @J_F, I wrote the following function:

    List <- vector("list", Length)
    
    deque <- function(List, x)
    {
      Length = length(List)
      List <- c(List, x)
      if (length(List) > Length)
      {
        List[1] <- NULL
      }
      return(List)
    }