mylist = []
for this in that:
df = 1
mylist.append(df)
基本上只是创建一个空列表,然后将循环中创建的对象添加到其中。
我只看到 R 解决方案,其中必须指定新元素的索引(比如
mylist[[i]] <- df
),因此需要创建索引 i
在循环。有没有比在最后一个元素之后追加更简单的方法。
最佳答案
有一个函数叫 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 循环更好(不一定更快),但这取决于循环的实际目的。回答 OP 的评论:关于使用
ggplot2
并将绘图保存到列表中,这样的操作会更有效: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分享 Comparison of c()
and append()
functions :
Concatenation (c) is pretty fast, but append is even faster and therefor preferable when concatenating just two vectors.
关于r - 如何在不跟踪索引的情况下将元素 append 到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962474/