'How to replace NA value with 0 in r data.table? [duplicate]

I have a list of variables with missing values. I would like for those selected columns to replace that missing value by 0 (or a blank space or whatever).

How can I achieve this with data.table ? My attempts with nafill failed because my variables aren't numeric.

start <- data.table::data.table(DAS1 = c("2",NA,"x","2","1","2","1"),
                       DAS2 = c("x","y","2","2", NA,"1","2"),
                       DAS3 = c("1","1","y", NA, NA,"y", NA))

end <- data.table::data.table(DAS1 = c("2","0","x","2","1","2","1"),
                       DAS2 = c("x","y","2","2", "0","1","2"),
                       DAS3 = c("1","1","y", "0", "0","y", "0"))


Solution 1:[1]

As a data.table is also a data.frame, this will work :

start[is.na(start)]<-0

all.equal(start,end)
#[1] TRUE

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1