Zac*_*ach 6 r data-manipulation data-management rolling-computation
假设我有一个具有以下结构的数据框:
DF <- data.frame(x = 0:4, y = 5:9)
> DF
x y
1 0 5
2 1 6
3 2 7
4 3 8
5 4 9
Run Code Online (Sandbox Code Playgroud)
将"DF"转换为具有以下结构的数据框的最有效方法是什么:
w x y
1 0 5
1 1 6
2 1 6
2 2 7
3 2 7
3 3 8
4 3 8
4 4 9
Run Code Online (Sandbox Code Playgroud)
其中w是滚动数据帧'DF'的长度为2的窗口.窗口的长度应该是任意的,即长度为3的产量
w x y
1 0 5
1 1 6
1 2 7
2 1 6
2 2 7
2 3 8
3 2 7
3 3 8
3 4 9
Run Code Online (Sandbox Code Playgroud)
我有点难以理解这个问题,因为数据框也可以包含任意数量的列,即w,x,y,z等.
/编辑2:我意识到编辑1有点不合理,因为xts似乎没有处理每个数据点的多个观察
Pra*_*ani 10
我的方法是使用该embed
功能.首先要做的是在向量中创建一个滚动的索引序列.采取数据框架:
df <- data.frame(x = 0:4, y = 5:9)
nr <- nrow(df)
w <- 3 # window size
i <- 1:nr # indices of the rows
iw <- embed(i,w)[, w:1] # matrix of rolling-window indices of length w
> iw
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 3 4
[3,] 3 4 5
wnum <- rep(1:nrow(iw),each=w) # window number
inds <- i[c(t(iw))] # the indices flattened, to use below
dfw <- sapply(df, '[', inds)
dfw <- transform(data.frame(dfw), w = wnum)
> dfw
x y w
1 0 5 1
2 1 6 1
3 2 7 1
4 1 6 2
5 2 7 2
6 3 8 2
7 2 7 3
8 3 8 3
9 4 9 3
Run Code Online (Sandbox Code Playgroud)