我正在寻找r /questions/tagged/r相当于这个简单的代码python /questions/tagged/python
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
##
Note: Using 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))
})
Thanks to @Wen https://stackoverflow.com/questions/45962474/how-to-append-an-element-to-a-list-without-keeping-track-of-the-index/45962721#comment78884250_45962474 for sharing Comparison of c() and append() functions http://rfunction.com/archives/2087:
连接 (c) 相当快,但追加速度更快,因此在仅连接两个向量时更可取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)