Is there a way to restart a for loop after it has completed iterating?

Viewed 31

I have a parameter set before a very complicated nested for loop.

Once the for loop is completed, I would like to set p to p+1 and then restart the loop at the first iteration. I can do the first fairly easily with an if statement, but is there a way to restart the loop from the first iteration? Currently, it just stops after setting i to 1.

p <- 19
a <- matrix()
source <- c(1:420)
for (i in 1:length(source)) {
  a[i] <- p + i
  if (i==length(source)) {
    p <- p+1
    i <- 1
  }
}
1 Answers

The usual pattern people use for this is to nest for loops, one for each axis. I don't know if there's something that prevents it from working specifically in R but it would probably look something like this.

a <- matrix()
source <- c(1:420)
for (p in 19:20 ) {
  for (i in 1:length(source)) {
    a[i] <- p + i
  }
}
Related