How to add elements to a list in R (loop)

R

R Problem Overview


I would like to add elements to a list in a loop (I don't know exactly how many)

Like this:

l <- list();
while(...)
   l <- new_element(...);

At the end, l[1] would be my first element, l[2] my second and so on.

Do you know how to proceed?

R Solutions


Solution 1 - R

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Solution 2 - R

The following adds elements to a vector in a loop.

l<-c()
i=1

while(i<100) {
    
    b<-i
    l<-c(l,b)
    i=i+1
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilippe RemyView Question on Stackoverflow
Solution 1 - RkonvasView Answer on Stackoverflow
Solution 2 - RJasonView Answer on Stackoverflow