Home > database >  Use a function to calculate probabilities of non-zero values per window in rolling windows in R
Use a function to calculate probabilities of non-zero values per window in rolling windows in R

Time:04-11

I have a matrix with 0 and 1 as the following:

set.seed(9900)
M = matrix(rbinom(50, 1, 0.2), 5, 10)
> M
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    0    0    0    0    0    0    0    0     0
[2,]    0    0    0    0    0    1    0    0    0     0
[3,]    0    0    0    0    0    0    0    0    0     0
[4,]    0    0    0    1    0    0    0    0    0     0
[5,]    0    1    0    1    0    0    0    0    0     0

And I want to have the probability that the sum of the rows contains non-zero elements. For the entire M matrix I can use the following code:

prob = sum(colSums(t(M) !=0) !=0)/nrow(M)
> prob
[1] 0.8

However, I want to use this function in rolling or sliding windows, containing 5 columns at a time and moving every one column, so that I would have one "prob" per window. I know the "zoo" package has some functions to work with rolling windows, but I do not know how to adapt it to my case. Any ideas? Thanks!

CodePudding user response:

Use zoo::rollapply. I'm not entirely sure what your expected output, but here's a code that compute your functions for every two rows:

library(zoo)
rollapply(t(M), width = 5, FUN = \(x) sum(rowSums(x !=0) != 0) / nrow(M), by.column = F, align = "right")
[1] 0.6 0.6 0.4 0.4 0.2 0.2

Note: \ is a shortcut for function in lambda-like functions since R 4.1.

  • Related