nigmastar
nigmastar

Reputation: 470

Difference between complete.cases and !is.na

I just discovered this new function it seems to me to an improved version of !is.na, maybe wrapped into an apply(df, 1). Am I correct or the following:

> a<-c(1,2,4,NA,6,8)
> identical(complete.cases(a), !is.na(a))
[1] TRUE

it's not always true?

Upvotes: 4

Views: 3707

Answers (2)

Anil Garlapati
Anil Garlapati

Reputation: 227

Lets take a vector r1 and matrix/table r2 as below and interpret the results

> r1
 [1] 11.3 10.4   NA 11.7 10.8 11.7 10.1  9.8 12.1  1.5  1.8
> r2
    speed mxPH mnO2
60 medium 6.60 11.3
61 medium 6.50 10.4
62 medium 6.40   NA
63   high 7.83 11.7
64   high 7.57 10.8
65   high 7.19 11.7
66   high 7.44 10.1
67   high 7.14  9.8
68   high 7.00 12.1
69 medium 7.50  1.5
70 medium 7.50  1.8

is.na and complete.cases work same way for a vector

> **is.na(r1)**
 [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> **complete.cases(r1)**
 [1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

Now lets see both what both commands give for a 2 dimensional data

as you can see is.na acted upon individual value but complete.cases acted on ROW level

> **is.na(r2)**
   speed  mxPH  mnO2
60 FALSE FALSE FALSE
61 FALSE FALSE FALSE
62 FALSE FALSE  TRUE
63 FALSE FALSE FALSE
64 FALSE FALSE FALSE
65 FALSE FALSE FALSE
66 FALSE FALSE FALSE
67 FALSE FALSE FALSE
68 FALSE FALSE FALSE
69 FALSE FALSE FALSE
70 FALSE FALSE FALSE

> **complete.cases(r2)**
 [1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

Upvotes: 1

mnel
mnel

Reputation: 115392

For an atomic vector, complete.cases and is.na will be identical. For more complex objects this will not be the case.

Eg, for, a data.frame is.na.data.frame will return a logical matrix of the same dimension as the input.

test <- data.frame(a, b =1)

is.na(test)
#          a     b
# [1,] FALSE FALSE
# [2,] FALSE FALSE
# [3,] FALSE FALSE
# [4,]  TRUE FALSE
# [5,] FALSE FALSE
#[6,] FALSE FALSE
complete.cases(test)
# [1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE

Upvotes: 6

Related Questions