How to remove rows with inf from a dataframe in R

后端 未结 6 652
自闭症患者
自闭症患者 2020-12-29 03:50

I have a very large dataframe(df) with approximately 35-45 columns(variables) and rows greater than 300. Some of the rows contains NA,NaN,Inf,-Inf values in

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 04:28

    To keep the rows without Inf we can do:

    df[apply(df, 1, function(x) all(is.finite(x))), ]
    

    Also NAs are handled by this because of:
    a rowindex with value NA will remove this row in the result.

    Also rows with NaN are not in the result.

    set.seed(24)
    df <- as.data.frame(matrix(sample(c(0:9, NA, -Inf, Inf, NaN),  20*5, replace=TRUE), ncol=5))
    df2 <- df[apply(df, 1, function(x) all(is.finite(x))), ]
    

    Here are the results of the different is.~-functions:

    x <- c(42, NA, NaN, Inf)
    is.finite(x)
    # [1]  TRUE FALSE FALSE FALSE
    is.na(x)
    # [1] FALSE  TRUE  TRUE FALSE
    is.nan(x)
    # [1] FALSE FALSE  TRUE FALSE
    

提交回复
热议问题