How to check a data.frame for any non-finite

前端 未结 4 976
渐次进展
渐次进展 2021-01-01 20:57

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

4条回答
  •  半阙折子戏
    2021-01-01 21:30

    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
    

提交回复
热议问题