6

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

Community
  • 1
  • 1
Hack-R
  • 22,422
  • 14
  • 75
  • 131

2 Answers2

11

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
Hack-R
  • 22,422
  • 14
  • 75
  • 131
csgillespie
  • 59,189
  • 14
  • 150
  • 185
1

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
martin
  • 785
  • 5
  • 17