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
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