Replace all "-Inf" values in Data Frame with 0

I have a data frame (Log.df) that after I took the log of the values has returned many -Inf data points. Here is an example:

     [one] [two] [three]
[A]    2.3  -Inf  -Inf
[B]   -Inf   1.1   2.4

I want to replace all the -Inf with 0. I tried this code:

Log.df <- Log.df[Log.df == "-Inf"] <- 0

And this code:

Log.df <- Log.df[Log.df == -Inf] <- 0

Both returned a single value of 0 and wiped the whole set!

Try

Log_df
   one  two three
1  2.3 -Inf  -Inf
2 -Inf  1.4   1.2

Log_df %>% mutate(one = ifelse(one < 0,0, one)) %>% mutate(two = ifelse(two < 0,0,two)) %>% mutate(three = ifelse(three < 0, 0, three))
  one two three
1 2.3 0.0   0.0
2 0.0 1.4   1.2

If you have negative non-infinite values, just substitute 1e-9 or some other suitably small number.

Here is one way to do it. I used mutate_if in case your actual data frame has some columns that are not numeric. Are you sure that it is ok to effectively replace all of your zeros with ones in the pre-log data set?

DF <- data.frame(A = log(c(0, 2,0)), B = log(c(1,0,5)), C = log(c(4,4,0)))
DF
#>           A        B        C
#> 1      -Inf 0.000000 1.386294
#> 2 0.6931472     -Inf 1.386294
#> 3      -Inf 1.609438     -Inf
library(dplyr)

DF <- DF %>% mutate_if(is.numeric, function(x) ifelse(is.infinite(x), 0, x))
DF
#>           A        B        C
#> 1 0.0000000 0.000000 1.386294
#> 2 0.6931472 0.000000 1.386294
#> 3 0.0000000 1.609438 0.000000

Created on 2019-11-05 by the reprex package (v0.2.1)

2 Likes

Your first try was a good idea. This works correctly - just don't assign it to the whole data.frame too Log.df <-. That is why your whole set is replaced. Log.df <- Log.df[Log.df == -Inf] <- 0 assigns 0 to the Inf values but also to Log.df so erase the whole data.frame

Log.df <- data.frame(A = log(c(0, 2,0)), B = log(c(1,0,5)), C = log(c(4,4,0)))

Log.df[Log.df == -Inf] <- 0
Log.df
#>           A        B        C
#> 1 0.0000000 0.000000 1.386294
#> 2 0.6931472 0.000000 1.386294
#> 3 0.0000000 1.609438 0.000000

Created on 2019-11-06 by the reprex package (v0.3.0)

3 Likes

Thanks!!! This is the simplest it seems. And thank you to everyone else who put forth a solution!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.