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]