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 can I replace the missing values with the mean of each column within id? In my actual data I have many variables which for only ones I wish to replace so how could be done in a general way so that for example it is not replaced for var3 but only to var1 and var2?:
tomean=c("var1", "var2")
I tried something like this but I haven't found a solution:
dat[, (tomean) := mean(tomean, na.rm=TRUE), by=id, .SDcols = tomean]