R中的动态类数组结构? [英] Dynamic Array-Like Structure In R?

查看:25
本文介绍了R中的动态类数组结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 编程语言中,如何获取动态数组(如维基百科所述) 或等效的数据结构?我想要具有以下属性的东西:

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) 索引.

  1. O(1) indexing.

附加摊销 O(1).

O(N) 或更少浪费的空间.

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.

据我所知,使用列表不起作用 因为以下列方式附加到一个需要 O(N) 时间,而不是摊销 O(1):

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

推荐答案

不是每次都追加到列表中,而是预先分配一个固定的长度.然后,当列表已满时,按照维基百科文章中的描述将其翻倍.这应该会给你带来你想要的表现.

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)))
}

这篇关于R中的动态类数组结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆