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

问题描述 投票:3回答:5

我在寻找相当于这个简单的代码

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

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

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

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

r list append
5个回答
6
投票

有一个叫做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)非常快,但追加更快,因此当连接两个向量时更好。


2
投票
mylist <- list()
for (i in 1:100) {
     df <- 1
     mylist <- c(mylist, df)
}

2
投票

有:mylist <- c(mylist, df),但这通常不是R中推荐的方式。根据你想要达到的目标,lapply()通常是更好的选择。


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

0
投票

(澄清以前的评论)

使用

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))
© www.soinside.com 2019 - 2024. All rights reserved.