问题
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:
O(1) indexing.
Amortized O(1) appending.
O(N) or less wasted space.
Type parametric, i.e. can hold lists, user-defined objects, functions, matrices, etc., not just numbers.
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:
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)))
}
来源:https://stackoverflow.com/questions/8219613/dynamic-array-like-structure-in-r