R:在滚动窗口外创建数据框 [英] R: create a data frame out of a rolling window

查看:86
本文介绍了R:在滚动窗口外创建数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有以下结构的数据框:

Lets say I have a data frame with the following structure:

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

将 DF转换为具有以下结构的数据帧的最有效方法是什么:

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

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

其中w是在数据帧 DF中滚动的一个长度为2的窗口。该窗口的长度应该是任意的,即长度为3的结果。

Where w is a length 2 window rolling through the dataframe 'DF.' The length of the window should be arbitrary, i.e a length of 3 yields

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

我有点被这个问题困扰了,因为数据框还可以包含任意数量的列,即w,x,y,z等。

I am a bit stumped by this problem, because the data frame can also contain an arbitrary number of columns, i.e. w,x,y,z etc.

/ edit 2:实现的编辑1有点不合理,因为xts似乎无法处理每个数据点的多个观测值

/edit 2: I've realized edit 1 is a bit unreasonable, as xts doesn't seem to deal with multiple observations per data point

推荐答案

我的方法是使用 embed 函数。首先要做的是将索引的滚动序列创建为向量。取一个数据帧:

My approach would be to use the embed function. The first thing to do is to create a rolling sequence 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
  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

这篇关于R:在滚动窗口外创建数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆