R 双滑动窗
我想在for循环中创建一个双滑动窗口。示例数据集可能如下所示:R 双滑动窗,r,window,double,R,Window,Double,我想在for循环中创建一个双滑动窗口。示例数据集可能如下所示: 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,
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")
使用rollapply检查正确的输出(显然可以通过肉眼看到)
应该是:
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循环,因为我还有很多要添加的内容,但需要首先正确处理。谢谢。这很接近..修改自:
windowSize也许这可以帮助您:谢谢,但理想情况下,我希望将其作为for循环,因为我最终希望为windows添加更多条件。提示:I
从1
到nrow(a)
,您的子集运算符从I
到windowSize
。当i>windowSize
时会发生什么?
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(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
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)
}