将一些数据序列分成几个相邻的部分

Break some sequences of data into several adjacent pieces

我有几个序列,我想将其分成一系列相邻的数字。这些序列嵌套在一个个体列表中,因此包含相邻数字的 window 的大小因个体而异。以下是一些示例数据:

#The sequences of three individuals
sequences <- list(c(1,2,3,5,6), c(2,3,4,5,6), c(1,3,4,6,7))

#The window size that contains the adjacent numbers
#for the first individual, 2 adjacent numbers should be bonded together and for the second, 3 should be bonded, etc.
windowsize <- list(2,3,4)

#The breakdown of the adjacent numbers should look like:
[[1]]
[[1]][[1]]
[1] 1 2
[[1]][[2]]
[1] 2 3
[[1]][[3]]
[1] 3 5
[[1]][[4]]
[1] 5 6

[[2]]
[[2]][[1]]
[1] 2 3 4
[[2]][[2]]
[1] 3 4 5
[[2]][[3]]
[1] 4 5 6

[[3]]
[[3]][[1]]
[1] 1 3 4 6
[[3]][[2]]
[1] 3 4 6 7

我有一个比这大得多的数据集,所以我想也许写一个函数是实现这个目标的方法?谢谢!

我们可以将 Mapbase R 中的 embed 一起使用 - 遍历 'sequences'、'windowsize' 中 Map 的相应元素,使用 embed 创建一个矩阵,其中 dimension 指定为 'windowsize' 中的元素 (y) 并使用 asplit 按行拆分 (MARGIN = 1)

Map(function(x, y) asplit(embed(x, y)[, y:1], 1), sequences, windowsize)

-输出

[[1]]
[[1]][[1]]
[1] 1 2

[[1]][[2]]
[1] 2 3

[[1]][[3]]
[1] 3 5

[[1]][[4]]
[1] 5 6


[[2]]
[[2]][[1]]
[1] 2 3 4

[[2]][[2]]
[1] 3 4 5

[[2]][[3]]
[1] 4 5 6


[[3]]
[[3]][[1]]
[1] 1 3 4 6

[[3]][[2]]
[1] 3 4 6 7

如果我们想要 matrix,只需删除 asplit

Map(function(x, y) embed(x, y)[, y:1], sequences, windowsize)
[1]]
     [,1] [,2]
[1,]    1    2
[2,]    2    3
[3,]    3    5
[4,]    5    6

[[2]]
     [,1] [,2] [,3]
[1,]    2    3    4
[2,]    3    4    5
[3,]    4    5    6

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    1    3    4    6
[2,]    3    4    6    7

我们真的不需要在这里创建列表的列表,因为子列表都是矩形的。建议创建一个矩阵列表。我们使用了问题中的序列和窗口大小,但由于窗口大小可以用可能更有意义的数字向量表示。如果您仍然想要列表,请改用注释掉的 f。

library(zoo)
# split2 <- function(x) split(x, 1:nrow(x))
# f <- function(x, w) split2(rollapply(x, w, c))
f <- function(x, w) rollapply(x, w, c)
Map(f, sequences, windowsize)

给予:

[[1]]
     [,1] [,2]
[1,]    1    2
[2,]    2    3
[3,]    3    5
[4,]    5    6

[[2]]
     [,1] [,2] [,3]
[1,]    2    3    4
[2,]    3    4    5
[3,]    4    5    6

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    1    3    4    6
[2,]    3    4    6    7