How to catch which columns are throwing warnings in sapply?

407 Views Asked by At

I have a df, which should be all numerics, but which are all typed as characters. I am trying this:

sapply(df, as.numeric)

Which throws warnings:

There were 50 or more warnings (use warnings() to see the first 50)

I can ignore the warnings, but I would like to find where the issues are. How do I find which column(s) is/are throwing warnings?

This seems fairly basic, but I cannot figure out how to get it.

If it helps:

test <- as.data.frame(list(c("1","2","3"), c("1","poop","3")))
> sapply(test, as.numeric)
     c..1....2....3.. c..1....poop....3..
[1,]                1                   1
[2,]                2                  NA
[3,]                3                   3
Warning message:
In lapply(X = X, FUN = FUN, ...) : NAs introduced by coercion

What I would like is a function which tells me that column 2 is the problematic one.

1

There are 1 best solutions below

0
On

Thanks to @RichScriven.

This works:

test2 <- sapply(test, function(x) tryCatch(as.numeric(x), warning = function(w) "This one!!!"))
which(test2 == "This one!!!")