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
preallocate list in R
提问by Alex
It is inefficient in R to expand a data structure in a loop. How do I preallocate a list
of a certain size? matrix
makes this easy via the ncol
and nrow
arguments. How does one do this in lists? For example:
在 R 中循环扩展数据结构是低效的。如何预分配list
特定大小的 a?matrix
通过ncol
和nrow
参数使这变得容易。如何在列表中做到这一点?例如:
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
vector
can create empty vector of the desired mode and length.
vector
可以创建所需模式和长度的空向量。
x <- vector(mode = "list", length = 10)
回答by Justin
To expand on what @Jilber said, lapply
is 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是最好的选择