用与 R 中唯一对应的平均值填充 NA

Fill NA by mean values corresponding to unique in R

我想用来自另一列的唯一值的平均值填充数据 table 中的 NA 行。请查看预期的输出。我怎样才能在 R 中做到这一点?我更喜欢 data table 输出。

data2 <- data.table(Plan=c(11,11,11,11,91,91,91,91), Price=c(4.4,4.4,4.4,NA,3.22,3.22,3.22,NA), factor=c(0.17,0.17,0.17,NA,0.15,0.15,0.15,NA), Type=c(4,4,4,4,3,3,3,3))

data2
   Plan Price factor Type
1:   11  4.40   0.17    4
2:   11  4.40   0.17    4
3:   11  4.40   0.17    4
4:   11    NA     NA    4
5:   91  3.22   0.15    3
6:   91  3.22   0.15    3
7:   91  3.22   0.15    3
8:   91    NA     NA    3



Output
       Plan Price factor Type
    1:   11  4.40   0.17    4
    2:   11  4.40   0.17    4
    3:   11  4.40   0.17    4
    4:   11  4.40   0.17    4
    5:   91  3.22   0.15    3
    6:   91  3.22   0.15    3
    7:   91  3.22   0.15    3
    8:   91  3.22   0.15    3

我们可以使用 na.locf 按 'Plan' 分组来更改具有非 NA 前面值的 NA

library(zoo)
data2[, factor := na.locf(factor), by = Plan]

如果我们需要mean,使用na.aggregate

data2[, factor := na.aggregate(factor), by = Plan]

对于多列

nm1 <- c("Price", "factor"_
data2[, (nm1) := lapply(.SD, na.aggregate), by = Plan, .SDcols = nm1]