Data.table replaces NA with the average value for multiple columns and the identifier

If I have the following data table:

dat <- data.table("id"=c(1,1,1,1,2,2,2,2), "var1"=c(NA,1,2,2,1,1,2,2),
              "var2"=c(4,4,4,4,5,5,NA,4), "var3"=c(4,4,4,NA,5,5,5,4))
   id var1 var2 var3
1:  1   NA    4    4
2:  1    1    4    4
3:  1    2    4    4
4:  1    2    4   NA
5:  2    1    5    5
6:  2    1    5    5
7:  2    2   NA    5
8:  2    2    4    4

How to replace missing values ​​with the average value for each column in the identifier? In my actual data, I have many variables that are only for those that I want to replace, so how can this be done in a general way so that, for example, it is not replaced for var3, but only for var1 and var2 ?:

tomean=c("var1", "var2")

I tried something like this, but I did not find a solution:

dat[, (tomean) := mean(tomean, na.rm=TRUE), by=id, .SDcols = tomean]
+4
source share
2 answers

, get(). lapply() .

## determine the column names that contain NA values
nm <- names(dat)[colSums(is.na(dat)) != 0]
## replace with the mean - by 'id'
dat[, (nm) := lapply(nm, function(x) {
    x <- get(x)
    x[is.na(x)] <- mean(x, na.rm = TRUE)
    x
}), by = id]

dat

   id     var1     var2 var3
1:  1 1.666667 4.000000    4
2:  1 1.000000 4.000000    4
3:  1 2.000000 4.000000    4
4:  1 2.000000 4.000000    3
5:  2 1.000000 5.000000    5
6:  2 1.000000 5.000000    5
7:  2 2.000000 4.666667    5
8:  2 2.000000 4.000000    4

:. , , NA, nm. tomean.

tomean <- c("var1", "var2")
dat[, (tomean) := lapply(tomean, function(x) {
    x <- get(x)
    x[is.na(x)] <- mean(x, na.rm = TRUE)
    x
}), by = id]

   id     var1     var2 var3
1:  1 1.666667 4.000000    4
2:  1 1.000000 4.000000    4
3:  1 2.000000 4.000000    4
4:  1 2.000000 4.000000   NA
5:  2 1.000000 5.000000    5
6:  2 1.000000 5.000000    5
7:  2 2.000000 4.666667    5
8:  2 2.000000 4.000000    4
+6

apply , :

dat[,as.data.table(apply(.SD, 2, function(x) {x[is.na(x)] <- mean(x, na.rm=T); x})),by=id]
   id     var1     var2 var3
1:  1 1.666667 4.000000    4
2:  1 1.000000 4.000000    4
3:  1 2.000000 4.000000    4
4:  1 2.000000 4.000000    3
5:  2 1.000000 5.000000    5
6:  2 1.000000 5.000000    5
7:  2 2.000000 4.666667    5
8:  2 2.000000 4.000000    4
+1

Source: https://habr.com/ru/post/1618827/


All Articles