db001
db001

Reputation: 13

Create list of lists iteratively

I have a loop that repeats 100 times each time creating three objects e.g.:

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 a b 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?

Upvotes: 1

Views: 7104

Answers (2)

John Paul
John Paul

Reputation: 12664

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.

Upvotes: 8

Roland
Roland

Reputation: 132706

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.

Upvotes: 2

Related Questions