这是我使用过的以下功能
scores <- runif(n = 31, min = 0.35, max = 3.54)
fun <- function(dat, n) {
require(zoo)
N <- which(max(rollmean(dat, n)) == rollmean(dat, n))
output <- matrix(0, length(N), n)
for (i in 1:length(N)) {
output[i, ] <- dat[N[i]:(N[i] + n - 1)]
}
output
}
fun(scores, 15)
让我们从里到外跑吧
rollmean(dat, n)
您提到的 zoo 包为我们提供了滚动平均值,我们
max(rollmean(dat, n))
找到滚动平均值的最大值
max(rollmean(dat, n)) == rollmean(dat, n)
返回一个 TRUE/FALSE 向量,其中滚动均值等于最大值
N <- which(max(rollmean(dat, n)) == rollmean(dat, n))
返回最大值的索引。根据您的数据,您可能有多个序列获得最大值,我们决定使用以下循环返回所有序列
for (i in 1:length(N)) {
output[i, ] <- dat[N[i]:(N[i] + n -1)]
}
结果:
set.seed(12345)
scores <- runif(n = 31, min = 0.35, max = 3.54)
fun(scores, 15)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.588179 1.633928 0.9208938 3.385791 1.797393 1.39234
[,7] [,8] [,9] [,10] [,11] [,12]
[1,] 3.429675 2.606867 2.406091 1.593553 2.578354 2.085545
[,13] [,14] [,15]
[1,] 1.07243 1.895739 2.879693
fun(rpois(1000, 1), 10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 4 2 1 1 3 3 2 2
[2,] 1 4 2 1 1 3 3 2 2 1
[3,] 4 2 1 1 3 3 2 2 1 1