Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishing between infinity and negative infinity during value replacement in R

Tags:

r

infinity

There are some good examples of how to replace infinite values in R with NA in this thread.

For instance,

DT <- data.table(dat)
invisible(lapply(names(DT),function(.name) set(DT, 
           which(is.infinite(DT[[.name]])), j = .name,value =NA)))

However, this doesn't distinguish between positive (Inf) and negative infinity (-Inf).

I need to make this distinction because instead of just replacing the values with NA and throwing them out or imputing them, I'd like to try using the max non-infinite value for positive infinity and min non-infinity value for negative infinity (and things like that).

Is this possible?

Example input data

a <- c(-1,2,3,4,100/0,-100/0)

[1] -1 2 3 4 Inf -Inf

Example output data

[1] -1 1 2 3 4 4 -1

like image 662
Hack-R Avatar asked Apr 20 '16 19:04

Hack-R


2 Answers

Why not just combine is.infinite with a standard > or < comparison?

a <- c(-1,2,3,4,100/0,-100/0)

a[is.infinite(a) & a < 0] <- min(a[!is.infinite(a)])
a[is.infinite(a) & a > 0] <- max(a[!is.infinite(a)])
a
[1] -1  2  3  4  4 -1
like image 135
csgillespie Avatar answered Sep 22 '22 05:09

csgillespie


You may extract/replace any -Inf or Inf values in your vector in an even simpler fashion:

a <- c(-1,2,3,4,100/0,-100/0)   

a[a <= -Inf] <- min(a[is.finite(a)])    
a[a >= Inf] <- max(a[is.finite(a)])  

a
[1] -1  2  3  4  4 -1
like image 30
martin Avatar answered Sep 21 '22 05:09

martin