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).
Answer from konvas on Stack OverflowYou 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
}
How to append a list with multiple values?
list.append() vs set.add()
I'm trying to create a for loop in a network model where at the end of the loop I append a list. I have the code to append the list in python and am trying to figure out to do it in R.
This is what I have in python: res.append((S/G.number_of_nodes(),I/G.number_of_nodes(),SV/G.number_of_nodes(),IV/G.number_of_nodes()))
Can anyone tell me a function in R that would be analogous to the .append function in python?
Is there any reason why list uses append() and set uses add() function?* For me both append() and add() does the same thing, adds an element to the list of set. Why different method names were chosen?
* not function, but method