Dynamic Array-Like Structure In R?

2019-05-11 15:05发布

In the R programming language, how do I get a dynamic array (as described on Wikipedia) or equivalent data structure? I want something with the following attributes:

  1. O(1) indexing.

  2. Amortized O(1) appending.

  3. O(N) or less wasted space.

  4. Type parametric, i.e. can hold lists, user-defined objects, functions, matrices, etc., not just numbers.

  5. Appending without naming should be supported. Therefore, using an environment won't cut it.

From what I can tell, using a list doesn't work because appending to one the following way takes O(N) time, not amortized O(1):

foo <- list()
foo[[length(foo) + 1]] <- 1

1条回答
劫难
2楼-- · 2019-05-11 15:44

Instead of appending to the list each time, preallocate it with a fixed length. Then when the list is full, double it, as per the description on the Wikipedia article. This should give you the performance you're after.

foo <- vector("list", 1000)

# populate the list, with N >> 1000...
for(i in seq(N))
{
    foo[[i]] <- ...

    # if the list is full, extend it
    if(i == length(foo))
        foo <- c(foo, vector("list", length(foo)))
}
查看更多
登录 后发表回答