how to append an element to a list without keeping

2019-04-12 10:25发布

I am looking for the equivalent of this simple code in

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

basically just creating an empty list, and then adding the objects created within the loop to it.

I only saw R solutions where one has to specify the index of the new element (say mylist[[i]] <- df), thus requiring to create an index i in the loop.

Is there any simpler way than that to just append after the last element.

标签: r list append
5条回答
相关推荐>>
2楼-- · 2019-04-12 10:49

(Clarifying previous comment)

Use

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


Here's an example:

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

Now:

glmnet_classifier = do.call("cv.glmnet",
    c(list(x = dtm_train, y = train$target), glmnet_params))
查看更多
唯我独甜
3楼-- · 2019-04-12 10:50
mylist <- list()
for (i in 1:100) {
     df <- 1
     mylist <- c(mylist, df)
}
查看更多
甜甜的少女心
4楼-- · 2019-04-12 10:54

There is: mylist <- c(mylist, df) but that's usually not the recommended way in R. Depending on what you're trying to achieve, lapply() is often a better option.

查看更多
爷的心禁止访问
5楼-- · 2019-04-12 10:58
mylist <- list()
for (i in 1:100){
  n <- 1
  mylist[[(length(mylist) +1)]] <- n
}

This seems to me the faster solution.

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
查看更多
我想做一个坏孩纸
6楼-- · 2019-04-12 11:04

There is a function called 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 functions instead of a for loop is better but it depends on the actual purpose of your loop.

Answering OP's comment: About using ggplot2 and saving plots to a list, something like this would be more efficient:

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 for sharing Comparison of c() and append() functions:

Concatenation (c) is pretty fast, but append is even faster and therefor preferable when concatenating just two vectors.

查看更多
登录 后发表回答