【问题标题】:R: create a data frame out of a rolling windowR:从滚动窗口中创建一个数据框
【发布时间】:2011-07-29 10:34:42
【问题描述】:

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

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”转换为具有以下结构的数据框的最有效方法是什么:

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 产生

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 等。

/edit 2:我意识到编辑 1 有点不合理,因为 xts 似乎无法处理每个数据点的多个观察结果

【问题讨论】:

    标签: r data-manipulation data-management rolling-computation


    【解决方案1】:

    我的方法是使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 2023-03-21
      • 2021-06-12
      • 2016-09-23
      相关资源
      最近更新 更多