I want to replace NAs present in a column of a DATA TABLE with the mean of the same column. I am doing the following. But it is not working.
ww <- data.ta
While the zoo
answer is pretty nice it requires new dependency.
Using just data.table
you could do the following.
library(data.table)
# prepare data
ww = data.table(iris[1:5,])
ww[1, Sepal.Length := NA]
# solution
ww[, Sepal.Length.mean := mean(Sepal.Length, na.rm = TRUE) # calculate mean
][is.na(Sepal.Length), Sepal.Length := Sepal.Length.mean # replace NA with mean
][, Sepal.Length.mean := NULL # remove mean col
][] # just prints
While it may looks biggish comparing to zoo's, it is performance efficient as all steps are made using update by reference :=
.
It can also be easily tuned to replace NA with mean by group, just using by
argument in data.table.