Getting the rownumbers for all NA values of a column

Viewed 103

I have data as follows:

df <- as.data.frame(c(1,2,NA,4,5))
names(df)[1] <- "first_column"

  first_column
1            1
2            2
3           NA
4            4
5            5

I would like to get all the row numbers for which first_column is NA, so 3

I found ways to look up other values, i.e. which(grepl(2, df$first_column)) but not NA. Including NA values is apparently quite cumbersome (link). Is there an easier way to do this?

Any ideas?

3 Answers

We could use which with is.na

which(is.na(df))
[1] 3
which(is.na(df$first_column)==T)

With a tidyverse approach:

library(tidyverse)

df <- as.data.frame(c(1,2,NA,4,5))
names(df)[1] <- "first_column"

df %>% 
  mutate(second_column = ifelse(is.na(first_column), row_number(), NA))

#>   first_column second_column
#> 1            1            NA
#> 2            2            NA
#> 3           NA             3
#> 4            4            NA
#> 5            5            NA
Related