0

I have been trying to run this code (below here) and I have gotten that message "Error in if (temp[ii] == 0) { : missing value where TRUE/FALSE needed"...

temp = c(2.15, 3.5, 0, 0, 0, 1.24, 5.42, 6.87)
tm = length(temp)
for (i in 1:tm){
    if (temp[i] == 0) {
        counter3 = 1
        last = temp[i - 1]
        for (ii in i + 1:tm){
            if (temp[ii] == 0) {
                counter3 = counter3 + 1
            }
            if (temp[ii] != 0) {
                nxt = temp[i + counter3]
            }
        }
    }
}
Señor O
  • 17,049
  • 2
  • 45
  • 47
user2145596
  • 21
  • 1
  • 1
  • might help if you a) mentioned the language, B) fixed your formatting. – Paul Collingwood Mar 08 '13 at 16:24
  • 4
    -1 for not searching. This has been answered multiple times on this site, R-help, etc. Next time, search for the error before posting a question, you'll likely answer the question faster yourself. – Joshua Ulrich Mar 08 '13 at 16:55
  • 1
    this question has been answered at this thread: http://stackoverflow.com/questions/7355187/error-in-if-while-condition-missing-value-where-true-false-needed – pengchy Jul 04 '16 at 02:27

3 Answers3

3

Your problem is that temp[ii] is returning NA because ii goes out of bounds:

ii = i + 1:tm     #Your declaration for ii
ii = 1:tm + 1:tm  #Evaluates to

So ii will definitely be larger than tm (and therefore length(temp) at some point.

In order to better understand/debug for loops, consider printing just the indices:

for(i in 1:tm)
{
    print(i)
    for(ii in i + 1:tm)
        print(ii)
}
Señor O
  • 17,049
  • 2
  • 45
  • 47
  • thank you for your answering, but I still get the same message =/ – user2145596 Mar 08 '13 at 16:56
  • When I run that code I get the right answer for counter3=3 last=3.5 nxt=1.24 What it is all right! the only problem is the message that I have gotten and since Im not familiar with R, it has been hard to fix ! Thank you anyway – user2145596 Mar 08 '13 at 17:14
  • You're not making much sense. Why is it that you have `for(ii in i+1:tm)` instead of just `for(ii in 1:tm)`? – Señor O Mar 08 '13 at 18:25
2

At a guess I'm going to say that this is in R - if so I'm guessing that this line:

if (temp[i] == 0) (or temp[ii] == 0)

is resulting in an NA, and if conditions must have a TRUE or FALSE value.

Using a debugger if you can, I'd interrogate the value of temp[i] before the if block.

Sean Landsman
  • 7,033
  • 2
  • 29
  • 33
1

Difficult without knowing the language, but i think the issue is that the value in ii can be greater than the length of temp when i is at its upper bound. I'd have expected an index out of range or something similar but, without knowing the language, who knows! Hope you get your problem fixed.

GHC
  • 2,658
  • 5
  • 30
  • 35