Replace infinity in R

Replace Inf in R

Here is how to replace Inf in R if that is necessary for your data frame. It might appear in various situations, for example, when dividing with zero.
In my example in this post, I have infinity when detecting min or max values in each data frame row.

 

Here is a data frame where is necessary to replace Inf with NA in R.

df <- data.frame(
  agent = as.character(c("David", "John", "Paul")),
  v1 = as.numeric(c(701.82, NA, NA)),
  v2 = as.numeric(c(697.87, NA, 76.44)),
  v3 = as.numeric(c(283.02, NA, NA)),
  v4 = as.numeric(c(201.40, NA, 57.47))
)

df$minimum <- apply(df[2:5], MARGIN =  1, FUN = min, na.rm = T)

#Warning message:
#In FUN(newX[, i], ...) : no non-missing arguments to min; returning Inf

After running the last command, I’m getting the error message: no non-missing arguments to min; returning Inf.

Here is why. One of the rows contains only NA values. The same result would happen with the same calculation by using dplyr.

df

#  agent     v1     v2     v3     v4 minimum
#1 David 701.82 697.87 283.02 201.40  201.40
#2  John     NA     NA     NA     NA     Inf
#3  Paul     NA  76.44     NA  57.47   57.47

Min function in R has na.rm argument but doesn’t have inf.rm to handle infinity in R.

If you want to replace Inf in R, it is similar to other value replacing. For example, here is how to replace NA values.

First of all, you have to detect where Inf appears. Luckily there are two helpful R base functions like is.finite and is.infinite. Here is how to detect Inf values with is.finite.

is.finite(df$minimum)

#[1]  TRUE FALSE  TRUE

By using the ifelse function, you can replace Inf with NA or with zero one way or another.

df$minimum <- ifelse(is.finite(df$minimum), df$minimum, NA)

df

#  agent     v1     v2     v3     v4 minimum
#1 David 701.82 697.87 283.02 201.40  201.40
#2  John     NA     NA     NA     NA      NA
#3  Paul     NA  76.44     NA  57.47   57.47
df$minimum <- ifelse(is.infinite(df$minimum), NA, df$minimum)

If you want to use dplyr to replace Inf, you can do that like this.

require(dplyr)

df <- df %>% mutate(minimum = ifelse(is.finite(minimum), minimum, NA))