Bill
Bill

Reputation: 203

In R, how do you make a loop stop when the output of the loops stops changing?

I have a code like this:

library(igraph)
g <- make_empty_graph (2) %>%
  set_vertex_attr("a", value = 1) %>%
  add_vertices(2, color = 2, "a" = 2) %>%
  add_vertices(2, color = 4, "a" = 3) %>%
  add_edges(c(1,2, 2,1, 1,5, 5,1, 1,4 ,4,1)) %>%
  set_vertex_attr("xyz", value = 3)
plot(g)

for(i in 1:5) {
 print(V(g)$a)
 print(mean(V(g)$a == 1))
 print(i)

 V(g)$xyz = sapply(V(g), function(x) { NeighborList = neighbors(g, x) ; length(NeighborList[NeighborList$a == 2]) } )
 V(g)$a[V(g)$xyz==1]=2
if(time>5) {
 break
}
}

So, right now the command in the loop runs 5 times. But after i = 3, the proportion of nodes with a value of 1 for attribute "a" stops changing. I want to change the loop so that it will automatically break if the proportion of nodes with a value of 1 for attribute "a" stops changing.

So instead of repeating the commands 5 times, I want it to repeat it 3 times(when the outputs stop changing) and break the loop.

Upvotes: 1

Views: 70

Answers (1)

f.lechleitner
f.lechleitner

Reputation: 3812

I'm guessing V(g)$a is the value in question? If so, you could try this:

i <- 1
prev_value <- FALSE

repeat {
  print(V(g)$a)
  print(mean(V(g)$a == 1))
  print(i)

  V(g)$xyz = sapply(V(g), function(x) {
    NeighborList = neighbors(g, x)
    length(NeighborList[NeighborList$a == 2])
  })
  V(g)$a[V(g)$xyz == 1] = 2

  if (V(g)$a[i] == prev_value) {
    break
  }

  prev_value <- V(g)$a[i]
  i <- i + 1
}

This basically saves the value of the previous iteration and compares it to the value of the current iteration. If they're equal the loop breaks.

Upvotes: 2

Related Questions