简体   繁体   中英

Create list of lists iteratively

I have a loop that repeats 100 times each time creating three objects eg:

a<-TRUE
b<-1:20
c<-matrix(data=NA,ncol=2,nrow=10)

at the end of the first iteration I store these objects in a list:

myList<-list(a,b,c)

at the second iteration new ab and c are created which is stored in the same list overwriting the previous abc :

myList<-list(a,b,c)

Instead of overwriting the list I would like to add the new abc to the existing list.

Can the list be updated on each iteration to avoid overwrting it?

Can someone help?

If I understand the issue, you want a place to store your 100 lists. If so at the beginning do;

myList<-vector("list",100)

You now have a empty list with 100 slots. After each loop assign your output list to the correct slot. That is for iteration 34 put the output in mylist[[34]] . Each entry in myList will itself be a list of your results.

Try this:

fun <- function() {
  #insert here as much code as you desire
  a<-TRUE
  b<-1:20
  c<-matrix(data=NA,ncol=2,nrow=10)

  list(a, b, c)
} 

replicate(100, fun(), simplify=FALSE)

If your function depends somehow on the iteration, you should use lapply instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM