dplyr
包具有cummean
功能。如果你只是想为> 0,为v>0
V中选择值:
v <- c(1, 3, 0, 3, 2, 0)
dplyr::cummean(v[v>0])
#> [1] 1.000000 2.000000 2.333333 2.250000
如果你想重复的结果,你可以用食指和从动物园一个辅助功能发挥。
# Create a vector container for the result (here with NA values)
v_res <- v[NA]
# Fill cumsum where you want to calculate it (here v>0)
v_res[v>0] <- dplyr::cummean(v[v>0])
# Fill the gap with previous value
zoo::na.locf(v_res)
#> [1] 1.000000 2.000000 2.000000 2.333333 2.250000 2.250000
它与负值的作品以V太
v <- c(1, 3, 0, 3, -5, 2, 0, -6)
v_res <- v[NA]
v_res[v>0] <- dplyr::cummean(v[v>0])
zoo::na.locf(v_res)
#> [1] 1.000000 2.000000 2.000000 2.333333 2.333333 2.250000 2.250000 2.250000
你可以使用tidyverse
了。如果您的数据位于data.frame中,则此解决方案可能非常有用。
library(dplyr, warn.conflicts = F)
library(tidyr)
data <- data_frame(v = c(1, 3, 0, 3, 2, 0)) %>%
tibble::rowid_to_column()
res <- data %>%
filter(v > 0) %>%
mutate(cummean = cummean(v)) %>%
right_join(data, by = c("rowid", "v")) %>%
fill(cummean)
res
#> # A tibble: 6 x 3
#> rowid v cummean
#> <int> <dbl> <dbl>
#> 1 1 1 1.000000
#> 2 2 3 2.000000
#> 3 3 0 2.000000
#> 4 4 3 2.333333
#> 5 5 2 2.250000
#> 6 6 0 2.250000
pull(res, cummean)[-1]
#> [1] 2.000000 2.000000 2.333333 2.250000 2.250000
OK我看到,但它是不是平均本身。 '1 + 3 + 0/2'是三个值的总和,所以它应该是三个数值。我会更新答案以符合预期的结果 – cderv