list R中的预分配列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12464379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:53:28  来源:igfitidea点击:

preallocate list in R

performancerlistmemory

提问by Alex

It is inefficient in R to expand a data structure in a loop. How do I preallocate a listof a certain size? matrixmakes this easy via the ncoland nrowarguments. How does one do this in lists? For example:

在 R 中循环扩展数据结构是低效的。如何预分配list特定大小的 a?matrix通过ncolnrow参数使这变得容易。如何在列表中做到这一点?例如:

x <- list()
for (i in 1:10) {
    x[[i]] <- i
}

I presume this is inefficient. What is a better way to do this?

我认为这是低效的。有什么更好的方法可以做到这一点?

回答by Luciano Selzer

vectorcan create empty vector of the desired mode and length.

vector可以创建所需模式和长度的空向量。

x <- vector(mode = "list", length = 10)

回答by Justin

To expand on what @Jilber said, lapplyis specially built for this type of operation.

为了扩展@Jilber 所说的内容,它lapply是专门为此类操作而构建的。

instead of the for loop, you could use:

而不是 for 循环,您可以使用:

x <- lapply(1:10, function(i) i)

You can extend this to more complicated examples. Often, what is in the body of the for loop can be directly translated to a function which accepts a single row that looks like a row from each iteration of the loop.

您可以将其扩展到更复杂的示例。通常,for 循环体中的内容可以直接转换为一个函数,该函数接受看起来像循环每次迭代中的一行的单行。

回答by Jilber Urbina

Something like this:

像这样的东西:

   x <- vector('list', 10)

But using lapply is the best choice

但是使用lapply是最好的选择