Matt Bannert
Matt Bannert

Reputation: 28264

How to show indexes of NAs?

I have the piece to display NAs, but I can't figure it out.

try(na.fail(x))
> Error in na.fail.default(x) : missing values in object
# display NAs
myvector[is.na(x)]
# returns
NA NA NA NA

The only thing I get from this the length of the NA vector, which is actually not too helpful when the NAs where caused by a bug in my code that I am trying to track. How can I get the index of NA element(s) ?

I also tried:

subset(x,is.na(x))

which has the same effect.

EDIT:

y <- complete.cases(x)
x[!y]
# just returns another
NA NA NA NA

Upvotes: 29

Views: 47104

Answers (4)

Gudi Varaprasad
Gudi Varaprasad

Reputation: 1

R Code using loop and condition :

# Testing for missing values

is.na(x) # returns TRUE if x is missing

 y <- c(1,NA,3,NA)

 is.na(y) 

 # returns a vector (F F F T)

 # Print the index of NA values

 for(i in 1:length(y)) {
  if(is.na(y[i])) {
   cat(i, ' ')
  }
 }

Output is :

Click here

Also :

which(is.na(y))

Upvotes: 0

Srikanth G
Srikanth G

Reputation: 21

which(Dataset$variable=="") will return the corresponding row numbers in a particular column

Upvotes: 2

Jivlain
Jivlain

Reputation: 3658

You want the which function:

which(is.na(arr))

Upvotes: 53

doug
doug

Reputation: 70038

is.na() will return a boolean index of the same shape as the original data frame.

In other words, any cells in that m x n index with the value TRUE correspond to NA values in the original data frame.

You can them use this to change the NAs, if you wish:

DF[is.na(DF)] = 999

To get the total number of data rows with at least one NA:

cc = complete.cases(DF)
num_missing = nrow(DF) - sum(ok)

Upvotes: 4

Related Questions