双滑动window

Double sliding window

我想在 for 循环中创建双滑动 window。示例数据集可能如下所示:

    a <- structure(list(a = c(0.0961136, 0.1028192, 0.1106424, 0.1106424, 
0.117348, 0.117348, 0.117348, 0.122936, 0.1307592, 0.1307592, 
0.1318768, 0.1318768, 0.1385824, 0.1385824, 0.1318768, 0.1251712, 
0.1251712, 0.1251712, 0.1251712, 0.1251712)), .Names = "a", row.names = c(NA, 
-20L), class = "data.frame")

我目前的代码如下所示:

windowSize <- 5
windowStep <- 1
dat <- list()
for (i in seq(from = 1, to = nrow(a), by = windowStep)){
  window1 <- a[i:windowSize, ]
  window2 <- a[i:windowSize + windowSize, ]
  if (median(window1) <= 0.12 && (median(window1) >= 0.08)) {
    p <- "True"
 } else 
    p <- "not"

  dat[[i]] <- c(p)
}  
result <- as.data.frame(do.call(rbind, dat)) 

此示例表明我需要两个大小为 5(数据点)的 windows 一次将一个数据点从一个数据点滑到另一个数据点之前。这个例子没有使用 window 2 因为它不起作用!(我最终需要它来工作)但是只使用 window1 来计算每个步骤的中位数(在这种情况下)是有效的但是输出不正确。 if 语句询问如果 window 1 的中位数在 0.08 和 0.12 之间,则输出 "True" else "not."

for 循环的输出 =

1  True
2  True
3  True
4  True
5  True
6  True
7  True
8  True
9  True
10  not
11  not
12  not
13  not
14  not
15  not
16  not
17  not
18  not
19  not
20  not

使用 rollapply 检查的正确输出(显然可以用眼睛看到)

rollapply(a, 5, FUN = median, by = 1, by.column = TRUE, partial = TRUE, align = c("left"))

应该是:

1  True
2  True
3  True
4  not
5  not
6  not
7  not
8  not
9  not
10 not
11 not
12 not
13 not
14 not
15 not
16 not
17 not
18 not
19 not
20 not

如果可能的话,解决方案是否可以保留为 for 循环,因为我还有很多要添加但需要先把它弄好。谢谢。

接近..修改自:https://stats.stackexchange.com/questions/3051/mean-of-a-sliding-window-in-r

windowSize <- 10
windowStep <- 1
Threshold <- 0.12
a <- as.vector(a)
data <- a

slideFunct <- function(data, windowSize, WindowStep){
  total <- length(data)
  dataLength <- seq(from=1, to=(total-windowSize), by=windowStep)
  result <- vector(length = length(dataLength))
  for(i in 1:length(dataLength)){
    result[i] <- if (median(data[dataLength[i]:(dataLength[i]+windowSize)]) <= Threshold)
      result[i] <- "True"
    else
      result[i] <- "not"
  }
  return(result)
}