-4

I have a problem with my code where it keep returning this error code repeatedly. Would definitely appreciate the help!

for (i in 1:length(X)) {
  if (Q[i] < 30) {
    Q2[i] = Q[i]
    for (i in i:length(X)) {
      if (Q[i + 1] < 30) {
        Q[i] = 0
        break
      }
    }
  }
  else {
    Q2[i] = Q[i]
  }
}

Error in if (Q[i + 1] < 30) { : missing value where TRUE/FALSE needed

Machavity
  • 30,841
  • 27
  • 92
  • 100
Jj2000
  • 1
  • 2
    Try the loop from `1:(length(X) - 1)` – akrun Apr 01 '18 at 16:14
  • 2
    Welcome to SO. Have a look at https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example . It will help you asking question in a better way. So that it will be easier to get help – MKR Apr 01 '18 at 16:14
  • please provide some information on your data. What type of data is Q1 and Q2, are those dataframes, lists, vectors,....? Are there only num values or are there other values in it? are there NaN? – Michriko Apr 01 '18 at 16:42
  • X is a vector of numerical values. Q and Q2 are just empty vectors that I have created to store the results of the loop. – Jj2000 Apr 01 '18 at 21:19

1 Answers1

1

You're looping i through 1 to the length of X.

At if (Q[i + 1] < 30) { you are attempting to access the element i+1. On the last iteration of the loop, i will be greater than the length of X.

To avoid this, you should only loop up to length(X) - 1

Furthermore, your inner-loop is using the same index variable as your outer loop:

for (i in i:length(X)) {

Other than just being bad practice, it's probably not doing what you intended. You should probably change the inner loop index to j:

for (j in i:length(X)) {