Home > Enterprise >  Replace infinite values with max/min value of a row
Replace infinite values with max/min value of a row

Time:11-03

I have an example data frame that looks like this:

x <- data.frame(val1 = c(1,4,5,2), val2 = c(4,2,46,2), val3 = c(Inf, 1, 4, 9), val4 = c(13, 51, 3, -Inf))
> x
    val1 val2 val3 val4
1    1    4  Inf   13
2    4    2    1   51
3    5   46    4    3
4    2    2    9 -Inf

I'd like to replace the infinite values with the maximum value of each row. Similarly I'd like to replace the negative infinite values with the minimum value of each row. The final data frame would look as follows:

val1 val2 val3 val4
1    1    4   13   13
2    4    2    1   51
3    5   46    4    3
4    2    2    9    2

CodePudding user response:

Get the range for each row with the finite values and do the assignment with min/max based on the infinite value and the sign

x[] <- t( apply(x, 1, function(x) {
     x1 <- range(x[!is.infinite(x)])
     x[is.infinite(x) & sign(x) < 0] <- x1[1]
     x[is.infinite(x)] <- x1[2]
   x}))

-output

> x
  val1 val2 val3 val4
1    1    4   13   13
2    4    2    1   51
3    5   46    4    3
4    2    2    9    2

CodePudding user response:

You could use raster::clamp

as.data.frame(lapply(x, function(i) {
  raster::clamp(i, min(i[is.finite(i)]), max(i[is.finite(i)]))
}))
#>   val1 val2 val3 val4
#> 1    1    4    9   13
#> 2    4    2    1   51
#> 3    5   46    4    3
#> 4    2    2    9    3
  • Related