Search code examples
rvalidationna

How can I know WHICH NAs were introduced by coercion?


I have a somewhat messy dataset to clean. Some operations introduce NAs by coercion, but the dataset contains many NAs even without that. How can I determine which rows or elements had NAs introduced.

For example

a <- c(1,2,"three", rep(NA, times=10))
as.numeric(a)
 [1]  1  2 NA NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion 

Results in coercing the third element to a number. Is there a way to identify that it was the third element that caused this, rather than the other NA (non)values? Thank you!


Solution

  • Try

    which(is.na(as.numeric(a)) != is.na(a))
    3
    # Warning message:
    # In which(is.na(as.numeric(a)) != is.na(a)) : NAs introduced by coercion