我想通过忽略cummean
的组来使用NA
。这是示例数据。
data.frame(group1 = c(rep(1,3),rep(2,3),rep(3,3)),
val = c(c(NA,4,5),c(NA,NA,5),c(1,NA,3)))
如何通过忽略NA
来获得累积均值?
这是我想要的
c(NA,4,4.5,NA,NA,5,1,1,2)
答案 0 :(得分:2)
在计算replace
时,我们可以使用NA
忽略cummean
元素
library(dplyr)
library(tidyr)
df1 %>%
group_by(group1) %>%
mutate(new = replace(val, !is.na(val), cummean(val[!is.na(val)]))) %>%
fill(new)
-输出
# A tibble: 9 x 3
# Groups: group1 [3]
# group1 val new
# <dbl> <dbl> <dbl>
#1 1 NA NA
#2 1 4 4
#3 1 5 4.5
#4 2 NA NA
#5 2 NA NA
#6 2 5 5
#7 3 1 1
#8 3 NA 1
#9 3 3 2