Lalochezia
Lalochezia

Reputation: 497

Breaking out of nested for loop

I know there is an answer for how to break out of a for loop, but I'm still having trouble breaking out of a for loop when a condition is met, and then continuing onto the expression in the outer loop:

x <- 1:100
n <- as.factor(rep(c(1:5), 20))
data <- data.frame(x, n)
y <- 1:20
m <- 10

for(i in levels(n)){
  x.subset <- subset(data$x, data$n == i)

  for(j in 1:length(y)){
    x.big <- NULL
    x.big[j] <- x.subset[j]^2
    x.big.prev <- x.big #####

    if((mean(x.big.prev)-mean(x.big)) >=30){
          break
        } #end of if() statement
      } #end of j-loop
      plot(y, x.big.prev)
} #end of i loop

I'm trying to get the j loop to stop when the new x.subset (with a new set of values from i) has a greater mean than the previous x.subet by 30. I attempted that by comparing x.big.prev with x.big. I either keep getting one of two outcomes:

Error in if ((mean(x.big.prev) - mean(x.big)) >= 30) { : 
missing value where TRUE/FALSE needed

OR

It runs through all the iterations of j and just plots everything.

I think I put the expression x.big.prev <- x.big in the wrong place, but then again, I'm not sure where to put to allow for a comparison between the means of the two vectors.

Any ideas?

Upvotes: 1

Views: 826

Answers (1)

LAP
LAP

Reputation: 6685

You need to initialize x.big and x.big.prev outside of the inner loop. Also the redefining of x.big.prev inside the inner loop has to be done after the if()-statement. Try this:

for(i in levels(n)){
  x.subset <- subset(data$x, data$n == i)
  x.big <- NULL
  x.big.prev <- 1

  for(j in y){
    x.big[j] <- x.subset[j]^2

    if((mean(x.big.prev)-mean(x.big)) >=30){
          break
        } #end of if() statement
    x.big.prev <- x.big #####
      } #end of j-loop
      plot(y, x.big.prev)
} #end of i loop

Upvotes: 1

Related Questions