Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R dplyr: replace Inf values by 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

df[as.matrix(df) == Inf]  <- 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading