如何计算 R 中每 n 个先前值的平均值,并且仅当大于零时(不包括 "x" 值)

How to make an average of every n previous values in R and only if is above zero (excluding "x" value)

我有这个矩阵:

矩阵=

value1 value2 value3 value4 value5 value6 value7 value8 value9 value10
1 0 0 45 6 6 8 3 0 4 5
2 0 0 0 2 9 1 8 3 0 0
n n n n n n n n n n n

我想要的:

roll_aver =

value1 value2 value3 value4 value5 value6 value7 value8 value9 value10
1 0 0 45 25.5 19 16.25 5.75 5.67 5 4
2 0 0 0 2 5.5 4 5 3.5 4 5.5
n n n n n n n n n n n

我知道我可以通过以下方式进行滚动平均:

roll_aver <- t(apply(matrix, 1, function(x) rollmean(x, k=4, fill = 0, align ="right")))

但是通过这种方式,它会产生一个包含零的滚动平均值。

想象一下它的 excel 等同于 excel: averageif(行中最后4个的范围,>0)

我们可以通过遍历行来应用左侧第一个 non-zero 元素的 rollapply。然后,用 FUN for rollapply,排除零元素,当得到 mean

library(zoo)
t(apply(matrix, 1, FUN = function(x) {
   i1 <- cumsum(x != 0) > 0
   x[i1] <- rollapply(x[i1], width = 4, fill = 0, align = "right", 
    FUN = function(u) mean(u[u!=0]), partial = TRUE)
  x}))

-输出

   value1 value2 value3 value4 value5 value6 value7   value8 value9 value10
1      0      0     45   25.5   19.0  16.25   5.75 5.666667      5     4.0
2      0      0      0    2.0    5.5   4.00   5.00 5.250000      4     5.5

数据

matrix <- structure(c(0L, 0L, 0L, 0L, 45L, 0L, 6L, 2L, 6L, 9L, 8L, 1L, 
3L, 8L, 0L, 3L, 4L, 0L, 5L, 0L), .Dim = c(2L, 10L), .Dimnames = list(
    c("1", "2"), c("value1", "value2", "value3", "value4", "value5", 
    "value6", "value7", "value8", "value9", "value10")))