r - 如何在不跟踪索引的情况下将元素 append 到列表中?

标签 r list append

我在找 等效于 中的这个简单代码

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/

相关文章:

mysql - 我在 Mysql 数据库上有两个触发器,但我只能使用 SHOW TRIGGERS 列出一个

python - 通过递归公式改进纯Python素筛

java - 如何在不覆盖现有数据的情况下使用 DOM append 现有 XML 文件?在 java

swift - append 多个 VNCoreMLModel ARKit 和 CoreML

r - dplyr - 按 2 列分组并计算其中一列的唯一值

r - 当 classProbs=TRUE 时,在 R 中使用 Caret 的 SVM 的不同结果

python - 如何在 python 中轻轻地洗牌列表

javascript - 尝试从 append 的 html 中触发 onclick 事件

r - 使用多个值变量 R 进行转换

r - R zoo中的聚合函数返回错误