list 在 R 中的 for 循环中将元素添加到列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27153263/
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
Adding elements to a list in for loop in R
提问by Darko
I'm trying to add elements to a list in a for loop. How can I set the field name?
我正在尝试在 for 循环中将元素添加到列表中。如何设置字段名称?
L<-list()
for(i in 1:N)
{
#Create object Ps...
string<-paste("element",i,sep="")
L$get(string)<-Ps
}
I want every element of the list to have the field name dependent from i (for example, the second element should have "element2")
我希望列表中的每个元素都具有依赖于 i 的字段名称(例如,第二个元素应该具有“element2”)
How to do this? I think that my error is the usage of get
这该怎么做?我认为我的错误是使用get
回答by Rich Scriven
It seems like you're looking for a construct like the following:
似乎您正在寻找如下结构:
N <- 3
x <- list()
for(i in 1:N) {
Ps <- i ## where i is whatever your Ps is
x[[paste0("element", i)]] <- Ps
}
x
# $element1
# [1] 1
#
# $element2
# [1] 2
#
# $element3
# [1] 3
Although, if you know N
beforehand, then it is better practice and more efficient to allocate x
and then fill it rather than adding to the existing list.
虽然,如果您N
事先知道,那么分配x
然后填充它而不是添加到现有列表是更好的实践和更有效的做法。
N <- 3
x <- vector("list", N)
for(i in 1:N) {
Ps <- i ## where i is whatever your Ps is
x[[i]] <- Ps
}
setNames(x, paste0("element", 1:N))
# $element1
# [1] 1
#
# $element2
# [1] 2
#
# $element3
# [1] 3