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