【问题标题】:Break some sequences of data into several adjacent pieces将一些数据序列分成几个相邻的部分
【发布时间】:2022-01-19 18:01:56
【问题描述】:

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

#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

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

【问题讨论】:

    标签: r list sequence data-manipulation data-cleaning


    【解决方案1】:

    我们可以使用Mapbase R 中的embed - 循环遍历Map 中的'sequences'、'windowsize' 的相应元素,创建一个带有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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢@G。格洛腾迪克。是的我同意。矩阵输出列表看起来更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多