R 构建具有重叠观测值的数据框架
假设我有一个具有以下结构的数据帧:R 构建具有重叠观测值的数据框架,r,dataframe,rolling-computation,R,Dataframe,Rolling Computation,假设我有一个具有以下结构的数据帧: > DF <- data.frame(x=1:5, y=6:10) > DF x y 1 1 6 2 2 7 3 3 8 4 4 9 5 5 10 对于WindowsSize=2的本例,结果将是如下结构 x y 1 1 6 2 2 7 3 2 7 4 3 8 5 3 8 6 4 9 7 4 9 8 5 10 我可以做一个像这样的循环 DFResult <- NULL numBlocks <-
> DF <- data.frame(x=1:5, y=6:10)
> DF
x y
1 1 6
2 2 7
3 3 8
4 4 9
5 5 10
对于WindowsSize=2的本例,结果将是如下结构
x y
1 1 6
2 2 7
3 2 7
4 3 8
5 3 8
6 4 9
7 4 9
8 5 10
我可以做一个像这样的循环
DFResult <- NULL
numBlocks <- nrow(DF)-windowSize+1
for (i in 1:numBlocks) {
DFResult <- rbind(DFResult, DF[i:(i+horizon-1), ])
}
我试图在不应用任何聚合函数的情况下重复一块行。这不起作用,因为我缺少一些行
我有点被这个问题难住了,我四处寻找类似的问题,但没有找到任何问题。有谁有更好的主意吗 我们可以采用矢量化方法
i1 <- seq_len(nrow(DF))
res <- DF[c(rbind(i1[-length(i1)], i1[-1])),]
row.names(res) <- NULL
res
# x y
#1 1 6
#2 2 7
#3 2 7
#4 3 8
#5 3 8
#6 4 9
#7 4 9
#8 5 10
i1
rollapply(data=DF, width=windowSize, FUN=function(x) x, by.column=FALSE, by=1)
x y
[1,] 1 6
[2,] 2 7
[3,] 2 7
[4,] 3 8
i1 <- seq_len(nrow(DF))
res <- DF[c(rbind(i1[-length(i1)], i1[-1])),]
row.names(res) <- NULL
res
# x y
#1 1 6
#2 2 7
#3 2 7
#4 3 8
#5 3 8
#6 4 9
#7 4 9
#8 5 10