【问题标题】:Get row index number of first and last rows in a moving window获取移动窗口中第一行和最后一行的行索引号
【发布时间】:2022-01-13 03:30:51
【问题描述】:

我有一个数据框,其中:

df <- data.frame(position = c(1000,1156,3200,4629,5559,6100,7456,8208,9500,10000),
 col1 = c(0,0,1,1,1,0,0,1,1,0))

如果我想根据position中的值使用大小为2000的滑动窗口,滑动1000(从1000开始到10000结束),我可以使用什么命令来获取第一个的行索引号每个窗口的最后一行?例如,使用此数据框,输出将是:

|  window   | row_index1 | row_index2 |  
|   1       |     1      |    2       |
|   2       |     3      |    3       |
|   3       |     3      |    4       |
|   4       |     4      |    5       |
|   5       |     5      |    6       |
|   6       |     6      |    7       |
|   7       |     7      |    8       |
|   8       |     8      |    10      |

输出不必是表格格式,我只是在寻找一个命令来获取每个窗口中第一行和最后一行的索引号。

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 为什么 1000 包含在窗口 1 中,而 10 000 包含在窗口 8(而不是 9)中?
  • @DonaldSeinen 我希望滑动窗口以 10 000 结束,因为这是position 列中的最大值。比如第一个滑动窗口是 1000 到 3000,然后最后一个是 8000 到 10 000,所以总共 8 个窗口

标签: r sliding-window


【解决方案1】:

您可以使用带有 findInterval 的基本 R 方法(假设 df$position 似乎已排序)。这会产生一个矩阵,但您可以轻松转换为其他数据结构。

df <- data.frame(position = c(1000,1156,3200,4629,5559,6100,7456,8208,9500,10000),
                 col1 = c(0,0,1,1,1,0,0,1,1,0))

lims <- 1000*cbind(1:8, 1:8+2)

apply(lims, 1, function(x){
ind <- findInterval(x, df$position)
## you will need to add 1 to the first index given, because findInterval tells 
## you the index of the last value below your limit
c(ind[1]+1, ind[length(ind)])
}
)
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#> [1,]    2    3    3    4    5    6    7    8
#> [2,]    2    3    4    5    6    7    8   10

由reprex package (v2.0.1) 于 2021-12-08 创建

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2018-01-01
    • 2012-03-13
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多