1

My dataframe looks like this -

dataset = data.frame(ID=c(1:3),Count=c(22,NaN,13))

I'm trying to use the pipe operator to replace NaN with 0

dataset = dataset %>% replace('NaN',0)

However this doesn't work. I've looked at the solutions on this websites, but none seem to work.

Any inputs would be highly appreciated.

Varun
  • 1,129
  • 1
  • 13
  • 26
  • 8
    `dataset %>% mutate_at(vars(Count), ~replace(., is.nan(.), 0))` – Ronak Shah Jun 28 '19 at 11:35
  • 10
    `dataset[is.na(dataset)] – jay.sf Jun 28 '19 at 11:35
  • 1
    @DanM I added few more targets where `NaN` values are converted to 0. Should be fine now? – Ronak Shah Jun 28 '19 at 11:47
  • 1
    I dont think this question is a duplicate of the first and of the second links, because NAs are different from NaNs in R. For the third and fourth link, it might be a duplicate, but a specific package was asked in this question `dplyr`. However, NaNs are most often produced as a result of implossible calculations as 0/0 and sqrt or log of negative numbers. So probably best way to remove NaNs is by correcting the code before it is produced. – LuizZ Apr 12 '21 at 21:40
  • @jay.sf For this simple example, that works, but in general this will not work for a solution requiring the pipe operator like the OP wants. – Earlien Oct 25 '21 at 21:13

1 Answers1

3

This'll do it, and doesn't even require dplyr as it's in base:

dataset$Count[is.nan(dataset$Count)]<-0
DanM
  • 179
  • 1
  • 9