如何在不跟踪索引的情况下将元素附加到列表? [英] how to append an element to a list without keeping track of the index?
问题描述
mylist = []
for this in that:
df = 1
mylist.append(df)
基本上只是创建一个空列表,然后将在循环中创建的对象添加到其中.
basically just creating an empty list, and then adding the objects created within the loop to it.
我只看到 R 解决方案必须指定新元素的索引(比如 mylist[[i]] <- df
),因此需要创建索引 i
在循环中.
I only saw R solutions where one has to specify the index of the new element (say mylist[[i]] <- df
), thus requiring to create an index i
in the loop.
有没有比在最后一个元素后面追加更简单的方法.
Is there any simpler way than that to just append after the last element.
推荐答案
有个函数叫append
:
ans <- list()
for (i in 1992:1994){
n <- 1 #whatever the function is
ans <- append(ans, n)
}
ans
## [[1]]
## [1] 1
##
## [[2]]
## [1] 1
##
## [[3]]
## [1] 1
##
注意:使用 apply
函数而不是 for 循环更好(不一定更快),但这取决于您的实际目的循环.
Note: Using apply
functions instead of a for loop is better (not necessarily faster) but it depends on the actual purpose of your loop.
回答 OP 的评论:关于使用 ggplot2
并将绘图保存到列表中,这样的事情会更有效:
Answering OP's comment: About using ggplot2
and saving plots to a list, something like this would be more efficient:
plotlist <- lapply(seq(2,4), function(i) {
require(ggplot2)
dat <- mtcars[mtcars$cyl == 2 * i,]
ggplot() + geom_point(data = dat ,aes(x=cyl,y=mpg))
})
感谢 @Wen 分享c()的比较
code> 和 append()
函数:
Thanks to @Wen for sharing Comparison of c()
and append()
functions:
连接 (c) 非常快,但 append 更快,因此在仅连接两个向量时更可取.
Concatenation (c) is pretty fast, but append is even faster and therefor preferable when concatenating just two vectors.
这篇关于如何在不跟踪索引的情况下将元素附加到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!