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?
A more efficient approach to append an arbitrary number of elements to a list within a loop is to use the length function in each iteration. With the length function, you can get the number of elements in the list and assign each new element to the index behind the last element: length(mylist) + 1 .
To append an element in the R List, use the append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.
Use the append() method to add elements to a list while iterating over the list. Means you can add item in the list using loop and append method.
To append multiple elements to a Vector in R, use the append() method and pass the vector to the existing vector. It will spread out in the existing vector and add multiple elements to that vector.
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).
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With