Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how do I map numeric values to factors, including Inf and NaN?

Tags:

r

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

like image 465
Uri Laserson Avatar asked Aug 29 '11 02:08

Uri Laserson


People also ask

How do I convert a numeric variable to a factor in R?

For converting a numeric into factor we use cut() function.

Does number INF represent infinity in R?

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.

How do you assign infinity in R?

To check the NaN value in R, use the is. nan() function. That is it for infinity in the R tutorial.

How do you check for infinity in R?

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.


1 Answers

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.

like image 154
Chase Avatar answered Oct 06 '22 16:10

Chase