NaN is removed when using na.rm=TRUE

后端 未结 2 1754
旧时难觅i
旧时难觅i 2020-12-17 20:48

This reproducible example is a very simplified version of my code:

x <- c(NaN, 2, 3)

#This is fine, as expected
max(x)
> NaN

#Why does na.rm remove N         


        
相关标签:
2条回答
  • 2020-12-17 21:40

    It's a language decision:

    > is.na(NaN)
    [1] TRUE
    

    is.nan differentiates:

    > is.nan(NaN)
    [1] TRUE
    > is.nan(NA)
    [1] FALSE
    

    So you may need to call both.

    0 讨论(0)
  • 2020-12-17 21:48

    na.rm arguments in functions generally use is.na() or an analogous function.
    And since is.na(NaN) == TRUE, you then get the behavior you're observing.

    Now should NaN be treated as also NA? That is a different question ;)


    The best way around this is to explicitly tell R how to handle NaN One example:

    ifelse(any(is.nan(x)), NaN, min(x, na.rm=TRUE))
    
    0 讨论(0)
提交回复
热议问题