简体   繁体   中英

Distinguishing between infinity and negative infinity during value replacement in R

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM