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