mylist = []
for this in that:
df = 1
mylist.append(df)
Run Code Online (Sandbox Code Playgroud)
基本上只是创建一个空列表,然后将在循环中创建的对象添加到其中。
我只看到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
##
Run Code Online (Sandbox Code Playgroud)
注意:使用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))
})
Run Code Online (Sandbox Code Playgroud)
级联(c)非常快,但是append甚至更快,因此在仅级联两个向量时更可取。