vendredi 26 mai 2017

Replace NAs with 0 in all numeric columns using data.table in R

I want to compose code that will replace NAs with 0 in all numeric columns using data.table syntax.

My code is the following:

dt <- data.table(a = c(1:3,NA, NA, NA, 10:12 ), b = c(NA, NA, NA, 20:25), c = c(letters[1 : 7], NA, NA) )

> dt
    a  b  c
1:  1 NA  a
2:  2 NA  b
3:  3 NA  c
4: NA 20  d
5: NA 21  e
6: NA 22  f
7: 10 23  g
8: 11 24 NA
9: 12 25 NA


needed_names <- names(dt)[sapply(dt, is.numeric)]

dt_ <- dt[, lapply(.SD, function(x){if(is.na(x)) 0 else x}), .SDcols = needed_names] 

> dt_
    a b
1:  1 0
2:  2 0
3:  3 0
4: NA 0
5: NA 0
6: NA 0
7: 10 0
8: 11 0
9: 12 0

Could you tell me why my code is not working and what I should do to correct it?

Your advice will be appreciated.

Aucun commentaire:

Enregistrer un commentaire