mango123
mango123

Reputation: 39

Iteratively add to sequence in for loop R

I would like to iteratively add elements to a list over which I loop:

list = as.list(c(1,2,3))
list
for (x in list) {
  new_element = as.list(x^2)
  print(new_element)
  list = union(list, new_element)
}
list

However, R takes only the original 3 elements in the loop. I would like that the loop continues with the new elements. Any ideas on how I could adjust my code? Thanks!

Upvotes: 1

Views: 722

Answers (1)

John Coleman
John Coleman

Reputation: 52008

Use a while loop rather than a for loop, together with break to eventually terminate:

mylist = as.list(c(1,2,3))
i <- 1
while(TRUE){
  x <- mylist[[i]]
  if(x<10){
    new_element <- as.list(x^2)
    print(new_element)
    mylist = union(mylist, new_element)
    i <- i+1
  } else {
    break
  }
}

This causes mylist to have 7 items (lists containing 1,2,3,4,9,16,81 respectively) when the loop terminates.

Upvotes: 1

Related Questions