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
EDIT:
Gavin Simpson in comments reminds me that, in your situation, there are much easier ways to convert what is really an "NaN" to an "NA":
tester1 <- gsub("NaN", "NA", tester1)
tester1
# [1] "2" "2" "3" "4" "2" "3" "NA"
Solution:
To detect which elements of the character vector are NaN
, you need to convert the vector to a numeric vector:
tester1[is.nan(as.numeric(tester1))] <- "NA"
tester1
[1] "2" "2" "3" "4" "2" "3" "NA"
Explanation:
There are a couple of reasons that this isn't working as you expect it to.
First, although NaN
stands for "Not a Number", it does have class "numeric"
, and only makes sense inside of a numeric vector.
Second, when it is included in a character vector, the symbol NaN
is silently converted to the character string "NaN"
. When you then test it for nan
-ness, the character string returns FALSE
:
class(NaN)
# [1] "numeric"
c("1", NaN)
# [1] "1" "NaN"
is.nan(c("1", NaN))
# [1] FALSE FALSE