如何在不跟踪索引的情况下将元素追加到列表? [英] how to append an element to a list without keeping track of the index?
问题描述
我正在寻找 r 的问题,
I am looking for the r equivalent of this simple code in python
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 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))
})
Thanks to @Wen for sharing Comparison of c()
and append()
functions:
串联(c)相当快,但是append甚至更快,因此在仅连接两个向量时更可取.
这篇关于如何在不跟踪索引的情况下将元素追加到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!