Using R, I have a vector such as
a <- c(0.1,0.6,23,Inf,NaN)
I would like to convert it to something like
c("Finite","Finite","Finite","Inf","NaN")
with as little pain as possible. How is this done?
Thanks! Uri
For converting a numeric into factor we use cut() function.
Inf and -Inf are positive and negative infinity whereas NaN means 'Not a Number'. (These apply to numeric values and real and imaginary parts of complex values but not to values of integer vectors.) Inf and NaN are reserved words in the R language.
To check the NaN value in R, use the is. nan() function. That is it for infinity in the R tutorial.
is. infinite() Function in R Language is used to check if the vector contains infinite values as elements. It returns a boolean value for all the elements of the vector.
ifelse()
seems to work reasonably well:
b <- ifelse(is.finite(a), "Finite", ifelse(is.infinite(a), "Infinite", "NaN"))
> b
[1] "Finite" "Finite" "Finite" "Infinite" "NaN"
Technically, that returns a character vector, which can be converted with as.factor()
or just wrap factor()
around the initial call to return a factor to begin with...though character may suit your needs depending on what you need to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With