【问题标题】:how to append an element to a list without keeping track of the index?如何在不跟踪索引的情况下将元素附加到列表?
【发布时间】:2018-02-08 06:57:05
【问题描述】:

我正在寻找与 中此简单代码等效的

mylist = []
for this in that:
  df = 1
  mylist.append(df)

基本上只是创建一个空列表,然后将循环中创建的对象添加到其中。

我只看到 R 解决方案必须指定新元素的索引(比如 mylist[[i]] <- df),因此需要在循环中创建索引 i

有没有比在最后一个元素后面追加更简单的方法。

【问题讨论】:

标签: r python r list append


【解决方案1】:

有一个函数叫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

连接 (c) 非常快,但 append 更快,因此在仅连接两个向量时更可取。

【讨论】:

  • 难以置信。没找到。无论df 可能是什么,这都会起作用吗?它可能不是标量,而是整个数据框或 ggplot
  • @ℕʘʘḆḽḘ 检查更新。第一个适用于标量或非标量。
  • @Masoud 等一下。如果您查看 append() 函数的 R 代码,它只是执行:c(x, values)append()怎么会比c()快??? append() 方法应该给出与 c() 相同的结果...
  • @DamianoFantini 我不确定查看functionBody() 的输出是否是比较函数性能的正确方法。您可能想使用microbenchmark::microbenchmark() 并比较它们。
  • 你是对的。我比较了这里提出的 3 种方法。 append() 确实是最慢的。
【解决方案2】:
mylist <- list()
for (i in 1:100){
  n <- 1
  mylist[[(length(mylist) +1)]] <- n
}

在我看来,这似乎是更快的解决方案。

x <- 1:1000

aa <- microbenchmark({xx <- list(); for(i in x) {xx <- append(xx, values = i)} }) 
bb <- microbenchmark({xx <- list(); for(i in x) {xx <- c(xx, i)} } )
cc <- microbenchmark({xx <- list(); for(i in x) {xx[(length(xx) + 1)] <- i} } )

sapply(list(aa, bb, cc), (function(i){ median(i[["time"]]) / 10e5 }))
#{append}=4.466634 #{c}=3.185096 #{this.one}=2.925718

【讨论】:

    【解决方案3】:
    mylist <- list()
    for (i in 1:100) {
         df <- 1
         mylist <- c(mylist, df)
    }
    

    【讨论】:

      【解决方案4】:

      有:mylist &lt;- c(mylist, df),但这通常不是 R 中推荐的方式。根据您要实现的目标,lapply() 通常是更好的选择。

      【讨论】:

        【解决方案5】:

        使用

        first_list = list(a=0,b=1)
        newlist = c(first_list,list(c=2,d=3))
        
        print(newlist)
        

        $a [1] 0

        $b [1] 1

        $c [1] 2

        $d [1] 3


        这是一个例子:

        glmnet_params = list(family="binomial", alpha = 1,
        type.measure = "auc",nfolds = 3, thresh = 1e-4, maxit = 1e3)
        

        现在:

        glmnet_classifier = do.call("cv.glmnet",
            c(list(x = dtm_train, y = train$target), glmnet_params))
        

        【讨论】:

          猜你喜欢
          • 2012-06-27
          • 2012-10-05
          • 1970-01-01
          • 1970-01-01
          • 2013-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-01
          相关资源
          最近更新 更多