Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add elements to a list in R (loop) [duplicate]

Tags:

r

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?

like image 547
Philippe Remy Avatar asked Sep 26 '22 07:09

Philippe Remy


People also ask

How do you append to a list in a for loop in R?

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 .

How do I add an item to an existing list in R?

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.

How do you add elements to a loop list?

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.

How do I add multiple elements to a list in R?

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.


2 Answers

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).

like image 216
konvas Avatar answered Oct 19 '22 01:10

konvas


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
}
like image 9
Jason Avatar answered Oct 19 '22 00:10

Jason