I'm attempting to write a function that replaces NA in a numeric data.frame column with the mean, by group, of the data that is present for that variable. I realise this is imputation and there are packages for that, would prefer to do this myself, and the mean is just an example, will use a more sophisticated function. I've attempted to produce a mwe, but I get stuck near the end. I'm trying, where possible to stick to using tidyverse methods.
library(tidyverse)
## First create a little dataset for a minimum working example for questions
## three vectors
id <- c(rep("boh1", 6), rep("boh2", 6), rep("boh3", 6), rep("boh4", 6))
operator <- rep(c("op1", "op2"), each = 12)
nummos <- c(1, 4, 4, 3, 1, NA, 4, 2, 2, 3, 4, 4, NA, 1, 1, 5,
5, 4, 5, 3, 2, NA, 3, 3)
## combine vectors into df
dat1 <- data.frame(id, operator, nummos)
## group by two variables and get mean of variable by group
dat2 <- dat1 %>%
group_by(id, operator) %>%
summarize(mean = mean(nummos, na.rm=TRUE))
## now stuck, how to replace NA by mean value appropriate for that group?