0

I wonder how to replace the Inf values by 0 across all columns in the dataframe? I have tried several examples, but most answers work only for the vectors, not for the whole dataframe, eg. here or replace NA but not Inf. I am sure there has to be some more ellegant way directly in dplyr!

Dummy example:

df <- data.frame(vals <- c(1, Inf, NA, NaN))

Not working conversions:

df[!is.finite(df)] <- 0

df %>% mutate(across(everything(), !is.finite(), -99))

Errors:

Error in is.finite(df) : default method not implemented for type 'list'

or

Error in `mutate()`:
! Problem while computing `..1 =
  across(everything(), !is.finite(), -99)`.
Caused by error in `is.finite()`:
! 0 arguments passed to 'is.finite' which requires 1
maycca
  • 3,848
  • 5
  • 36
  • 67

2 Answers2

2
df[as.matrix(df) == Inf]  <- 0
1
do.call(data.frame,lapply(df, function(x) replace(x, is.infinite(x),0)))

From this post https://stackoverflow.com/a/12188551/16730940

Paul Stafford Allen
  • 1,840
  • 1
  • 5
  • 16