I\'d like to check if a data.frame has any non-finite elements.
This seems to evaluate each column, returning FALSE for each (I\'m guessing its evaluating the data.f
Your solution of calling as.matrix will only work if the data.frame only has numeric columns. Otherwise, the matrix will typically become a character matrix and the result will be false everywhere...
@joran has a good approach, but you'll have problems with factor columns unless to add a method for factors too etc...
is.finite(letters[1:3]) # FALSE - OK
is.finite(factor(letters[1:3])) # TRUE - WRONG!!
is.finite.factor <- function(obj){
logical(length(obj))
}
is.finite(factor(letters[1:3])) # FALSE - OK
Also, if you want the check to be as fast as possible, you should avoid sapply and go for vapply instead.
d <- data.frame(matrix(runif(1e6), nrow=10), letters[1:10])
# @joran's method
is.finite.data.frame <- function(obj){
sapply(obj,FUN = function(x) all(is.finite(x)))
}
system.time( x <- is.finite(d) ) # 0.42 secs
# Using vapply instead...
is.finite.data.frame <- function(obj) {
vapply(obj,FUN = function(x) all(is.finite(x)), logical(1))
}
system.time( y <- is.finite(d) ) # 0.20 secs
identical(x,y) # TRUE