Home > OS >  Getting the NA's introduced by coercion from a data frame
Getting the NA's introduced by coercion from a data frame

Time:11-05

I have data as follows:

library(data.table)
dat <- fread("A B C
              1 2 4
              1 1 1
              one 3 5")

When converting an entire data.frame to numeric, I want to know which NA's were introduced by coercion.

Seeing the answer to this question, I tried:

which(is.na(as.numeric(dat)) != is.na(dat))

But this gives the error:

Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'x' in selecting a method for function 'which': 'list' object cannot be coerced to type 'double'

I also tried:

for (i in seq_along(dat)) {
  which(is.na(as.numeric(dat[,i])) != is.na(dat[,i]))
}

Resulting in:

Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'x' in selecting a method for function 'which': j (the 2nd argument inside [...]) is a single symbol but column name 'i' is not found. Perhaps you intended DT[, ..i]. This difference to data.frame is deliberate and explained in FAQ 1.1.

And finally:

for (i in seq_along(dat)) {
    which(is.na(as.numeric(dat[,..i])) != is.na(dat[,..i]))
}

For which I again get:

Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'x' in selecting a method for function 'which': 'list' object cannot be coerced to type 'double'

How can I apply this solution to a data.frame or data.table?

CodePudding user response:

Maybe

which(is.na(as.numeric(unlist(dat))) != is.na(dat))
  • Related