ts <- c(1,3,5,2,4,3,2,5,6,1,3,2,4,10,15,20,24,34,40)
#shows elements where difference between x and x + lagth element is greater than 10
diffts <- diff(ts)
rollingwindow <- 5
# option 1
avgslope1 <- vector(mode = "numeric", length = (length(ts)-rollingwindow))
for ( i in 1 : (length(ts)-rollingwindow))
{
avgslope1[i] <- round(mean(ts[i:(i+rollingwindow)]),2)
}
#option 2
avgslope2 <- vector(mode = "numeric", length = (length(ts)-rollingwindow))
for ( i in 1 : (length(diffts)-rollingwindow))
{
avgslope2[i] <- round(mean(diffts[i:(i+rollingwindow)]),2)
}
avgslope1 是 5 个值的滚动平均值。如果您运行ts[1 + which.max(diff(avgslope1))],您将获得接下来五个值的平均值变化最大的值。同样,ts[1 + which.max(diff(avgslope2))] 返回值的平均变化在接下来的 5 个元素中最高的元素。
> avgslope1
[1] 3.00 3.17 3.50 3.67 3.50 3.33 3.17 3.50 4.33 5.83 9.00 12.50 17.83 23.83
> avgslope2
[1] 0.17 0.33 0.17 -0.17 -0.17 -0.17 0.33 0.83 1.50 3.17 3.50 5.33 6.00 0.00
> ts
[1] 1 3 5 2 4 3 2 5 6 1 3 2 4 10 15 20 24 34 40