UPDATE see below
I am not sure how to populate a list or vector with elements in a while loop when there is no counter/iterator to index by. See below minimal example. I have a more complicated while loop that, like foo below, has a logical statement that doesn’t include a number, so it’s not clear to me how to populate the list vec with x. Is it possible to create some kind of iterator within the while loop so that each time you go through the while loop the iterator simply increases by one? I could then use this iterator to index the list vec?
foo <- function(){
names <- list("a","b","c")
vec <- list()
more <- TRUE
while(more == TRUE){
names <- rep(names, 2)
if(length(names) < 50) vec <- names
more <- length(names) < 50
}
vec
}
foo()
Thanks, this seems to work as I wanted now:
foo <- function(){
names <- list("a","b","c")
i <- 0
vec <- list()
more <- TRUE
while(more == TRUE){
i <- i + 1
names <- rep(names, 2)
if(length(names) < 50) vec[[i]] <- names
more <- length(names) < 50
}
vec
}
foo()
Using the approach where you construct your own iterator is very easy. Here is some example code that prints the numbers 1 through 10 in what could possibly be the least R like way to accomplish this task:
As you can see it’s pretty much exactly like you describe. You just increase the iterator at the top of the loop.