Replace NAs with mean of the same column of a data.table

前端 未结 6 774
不思量自难忘°
不思量自难忘° 2020-12-09 17:42

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         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 18:01

    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.

提交回复
热议问题