R: create data frame from rewind window

Suppose I have a data frame with the following structure:

DF <- data.frame(x = 0:4, y = 5:9) > DF xy 1 0 5 2 1 6 3 2 7 4 3 8 5 4 9 

What is the most efficient way to turn DF into a data frame with the following structure:

 wxy 1 0 5 1 1 6 2 1 6 2 2 7 3 2 7 3 3 8 4 3 8 4 4 9 

Where w is a window with a length of 2 passing through the DF data frame. The window length must be arbitrary, i.e. 3 exit lengths

 wxy 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 

I am a little puzzled by this problem, because a data frame may also contain an arbitrary number of columns, i.e. w, x, y, z, etc.

/ edit 2: I realized that editing 1 is a bit unreasonable, as xts doesn't seem to be dealing with a few data point observations

+6
r data-manipulation rolling-computation data-management
source share
1 answer

My approach would be to use the embed function. The first thing to do is create a sequence of cascades of indices into a vector. Take a data frame:

 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 xyw 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 
+8
source share

All Articles