0

I have a problem to solve in R language but I may need to add element in a loop while I am looping into it with a for, but the loop does not go through the new values.

I made a simple loop to explain the type of problem I have.

Here is the code:

c=c(1,2)
for(i in c){
    c=c(c,i+2)
    print(i)
}

And the result:

[1] 1
[1] 2

I would like this result:

[1] 1
[1] 2
[1] 3
[1] 4

It continues until I reach a condition.

Can someone tell me wether it is possible or not with an other way?

Thank you,

Robin

  • Perhaps you can use a `while` loop instead – KenHBS Nov 12 '17 at 13:08
  • Yes I just thought about it and it seems to work if I add a condition to stop it at a moment. But thank you!! – Robin Jesson Nov 12 '17 at 13:12
  • Care to explain the logic of this loop? How do you go from `c(1, 2)` to `1:4`? – Roman Luštrik Nov 12 '17 at 13:17
  • There are very few reasons to use loops in R - generally there is a better idiom. Given your comments in the answer you might be interested in: https://stackoverflow.com/questions/29730624/how-to-split-an-igraph-into-connected-subgraphs – bdecaf Nov 12 '17 at 13:47
  • I find a solution to my problem and I finally don't have to increase vectors. But thank you for all your help. – Robin Jesson Nov 12 '17 at 14:15

1 Answers1

2

You could use a while loop instead:

test <- c(1,2)
n    <- 1

while(n <= length(test)){
  if(n == 5){
    print(test)
    break
  }
  print(test[n])
  test <- c(test, n+2)

  n <- n + 1
}

Note that in this case, the loop will keep on printing forever, so you should add some other condition to stop the loop at some point (here I quit it at 5).

Sidenote: You use c as a name for c(1,2). That's generally a bad idea, because c is reserved for defining vectors in R. It's always a good idea to avoid using names that are already used for other things by R itself.

KenHBS
  • 6,756
  • 6
  • 37
  • 52
  • Thank you (I have used c just for this example but I will care of your note next time!), just a question, does break stop the program or stop the loop? – Robin Jesson Nov 12 '17 at 13:16
  • This is reaching your pocket around your ass. `n`, if needs to be there, should be hard coded. This is just creating a fancy infinite loop. Keep in mind that growing objects, if possible, should be avoided. – Roman Luštrik Nov 12 '17 at 13:17
  • @RomanLuštrik I'm not sure what you mean by the answer reaching my pocket around my ass. I'm also not sure what's wrong with a fancy loop, if that's what's asked for. – KenHBS Nov 12 '17 at 13:22
  • Actually I am working on a graph, it is just about adding the neigbours of a vertex in a list so it is a finite set and won't generate an infinite loop. – Robin Jesson Nov 12 '17 at 13:24