Rilcon42
Rilcon42

Reputation: 9763

NA in list considered numeric. How to convert to NA object?

I have a vector that I am attempting to replace values in using if/else. It replaces all values except NA. Can someone tell me why?

My suspicion is that the NA are being treated as numbers (based on checking the class of the NA list value which returns numeric) but if they are being treated that way how can I get R to see them as NA objects so my if statement works?

> V(g)$label
  [1] 13  9 17 34  8 15  0 10 19 21  9 12 23 12 19 25 12 23 20 13 35  1  3  0  0 34 42 10 26 24 17 21 14  0  0  5  8 25  1 38 21  7 28  1  7  5  2  0 33  9  0  3 24  8 28 31  1  4 12 42 18 14 22 44  7 20 17 25 16 20 15
 [72]  8 13 45  8 32 13 25 15 33 15 13 52 37  2  4 27 41 12 33 26  4  0  7 37 43 24 23 22  9  3  7  8 13 20  0  0  0  9 10  1  2 18 16  0  0  8 11  0  0  0 NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> class(V(g)$label[130])
[1] "numeric"
> V(g)$label[130]
[1] NA

########converts values

V(g)$label <- ifelse(as.numeric(V(g)$label) < 10, 1, 
                ifelse(as.numeric(V(g)$label) >= 30, 3, 
                ifelse(is.na(V(g)$label),999,2)))
> V(g)$label
  [1]  2  1  2  3  1  2  1  2  2  2  1  2  2  2  2  2  2  2  2  2  3  1  1  1  1  3  3  2  2  2  2  2  2  1  1  1  1  2  1  3  2  1  2  1  1  1  1  1  3  1  1  1  2  1  2  3  1  1  2  3  2  2  2  3  1  2  2  2  2  2  2
 [72]  1  2  3  1  3  2  2  2  3  2  2  3  3  1  1  2  3  2  3  2  1  1  1  3  3  2  2  2  1  1  1  1  2  2  1  1  1  1  2  1  1  2  2  1  1  1  2  1  1  1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Upvotes: 0

Views: 77

Answers (2)

randy
randy

Reputation: 1081

The interpreter is not going to keep checking the other conditions once the first condition (whether the value is less than 10) evaluates to NA, because NA is not the same as FALSE. If you are somehow averse to checking for NA as the first condition, you can add it in stealthily to make your computer do more work:

V(g)$label <- 
    ifelse(V(g)$label < 10  & is.na(V(g)$label)==FALSE, 1, 
        ifelse(V(g)$label >= 30  & is.na(V(g)$label)==FALSE, 3, 
            ifelse(is.na(V(g)$label),999,2)))

But I do not know why would would want to check the same condition three times.

Upvotes: 0

B.Shankar
B.Shankar

Reputation: 1281

You need to check for NA first. This should work:

V(g)$label <- ifelse(is.na(V(g)$label), 999, 
                     ifelse(as.numeric(V(g)$label) < 10, 1, 
                     ifelse(as.numeric(V(g)$label) >= 30, 3, 2)))

Upvotes: 1

Related Questions