【发布时间】:2019-10-28 13:46:18
【问题描述】:
我正在尝试编写一个函数,将数值 data.frame 列中的 NA 替换为该变量存在的数据的平均值(按组)。我意识到这是估算,并且有相应的软件包,我更愿意自己做,平均值只是一个例子,将使用更复杂的函数。我试图制作一个 mwe,但我在接近尾声时被卡住了。我正在尝试,尽可能坚持使用 tidyverse 方法。
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?
【问题讨论】: