R can't convert NaN to NA

后端 未结 3 1361
心在旅途
心在旅途 2021-02-15 16:08

I have a data frame with several factor columns containing NaN\'s that I would like to convert to NA\'s (the NaN seems to be a problem for

3条回答
  •  眼角桃花
    2021-02-15 16:33

    You can't have NaN in a character vector, which is what you have here:

    > tester1 <- c("2", "2", "3", "4", "2", "3", NaN)
    > is.nan(tester1)
    [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE
    > tester1
    [1] "2"   "2"   "3"   "4"   "2"   "3"   "NaN"
    

    Notice how R thinks this is a character string.

    You can create NaN in a numeric vector:

    > tester1 <- c("2", "2", "3", "4", "2", "3", NaN)
    > as.numeric(tester1)
    [1]   2   2   3   4   2   3 NaN
    > is.nan(as.numeric(tester1))
    [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
    

    Then, of course, R can convert NaN to NA as per your code:

    > foo <- as.numeric(tester1)
    > foo[is.nan(foo)] <- NA
    > foo
    [1]  2  2  3  4  2  3 NA
    

提交回复
热议问题