Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locate index of rows in a dataframe that have the value of NA

Tags:

Suppose that we have the following data frame:

>  dataset1       x   1   1   2   2   3   3   4   NA   5   5 

I want to come up with a R command that computes the row index of the 1-column data frame that contains the value of 'NA'. More specifically, in above dataset1 example, such command would return 4 - because the 'NA' appears in the 4th row of the data frame. How can I make this happen? thank you!

like image 390
Jin-Dominique Avatar asked Nov 10 '13 21:11

Jin-Dominique


People also ask

How do you find the index of a particular value in a DataFrame?

To find the indexes of the specific value that match the given condition in Pandas dataframe we will use df['Subject'] to match the given values and index. values to find an index of matched value. The result shows us that rows 0,1,2 have the value 'Math' in the Subject column.

How do you find rows with missing data?

Extract rows/columns with missing values in specific columns/rows. You can use the isnull() or isna() method of pandas. DataFrame and Series to check if each element is a missing value or not. isnull() is an alias for isna() , whose usage is the same.

How do I find a row index number?

You can try as. numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df) . The which() function converts a TRUE/FALSE row index into row numbers.


2 Answers

As suggested by Ben Bolker, you can use both which and is.na as in:

> which(is.na(dataset1), arr.ind=TRUE)   row col 4   4   1  # NA is in row 4 and column 1 
like image 183
Jilber Urbina Avatar answered Oct 11 '22 06:10

Jilber Urbina


An alternative approach using functions from the tidyverse ecosystem:

> dataset1 %>%      rowid_to_column() %>%      filter(is.na(x))   rowid  x 1     4 NA 
like image 36
Ashirwad Avatar answered Oct 11 '22 04:10

Ashirwad