user2145596
user2145596

Reputation: 21

Error .. missing value where TRUE/FALSE needed

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]
            }
        }
    }
}

Upvotes: 0

Views: 6948

Answers (3)

Señor O
Señor O

Reputation: 17432

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)
}

Upvotes: 3

Sean Landsman
Sean Landsman

Reputation: 7197

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.

Upvotes: 2

GHC
GHC

Reputation: 2678

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.

Upvotes: 1

Related Questions