获取移动中第一行和最后一行的行索引号 window
Get row index number of first and last rows in a moving window
我有一个数据框,其中:
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))
如果我想使用大小为 2000 的滑动 windows,滑动 1000,(从 1000 开始到 10000 结束)基于 position
中的值,我可以使用什么命令来获取每个 window 的第一行和最后一行的行索引号?例如,对于这个数据框,输出将是:
| 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 |
输出不必是table格式,我只是在寻找一个命令来获取每个window中第一行和最后一行的索引号。
非常感谢任何帮助,谢谢!
您可以将基础 R 方法与 findInterval 结合使用(假定 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 创建
我有一个数据框,其中:
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))
如果我想使用大小为 2000 的滑动 windows,滑动 1000,(从 1000 开始到 10000 结束)基于 position
中的值,我可以使用什么命令来获取每个 window 的第一行和最后一行的行索引号?例如,对于这个数据框,输出将是:
| 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 |
输出不必是table格式,我只是在寻找一个命令来获取每个window中第一行和最后一行的索引号。
非常感谢任何帮助,谢谢!
您可以将基础 R 方法与 findInterval 结合使用(假定 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 创建