1

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!

4
  • It isn't clear what the intended output is. Are you trying to make an infinite loop? Commented Aug 26, 2021 at 10:16
  • you loop is supposed to continue till what? Commented Aug 26, 2021 at 10:20
  • Sorry for making it not clear. This is just an example and would indeed result in an indefinite loop. In my case, it will have an natural end because there are no more elements to add. I am scraping individuals from a datasource and want to scrape also all their siblings which are linked in the jsons of the individuals (my original list).- Is it clear now? Commented Aug 26, 2021 at 10:22
  • It might have been clearer if you had something like if(x < 10){...} as the body of the loop, along with an explicit intended output ((1,2,3,4,9,16,81)? ) Commented Aug 26, 2021 at 10:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks a lot! I haven't thought about a while loop (I am very new to R) and it is clever to use the index of the list!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.