Split vector separated by n zeros into different group

后端 未结 5 1225
情歌与酒
情歌与酒 2020-12-17 22:05

I have a vector x

x = c(1, 1, 2.00005, 1, 1, 0, 0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 0, 0, 1, 2, 3, 1, 3)

I need to split values sepa

5条回答
  •  遥遥无期
    2020-12-17 22:48

    Here's my attempt at it. This method replaces runs of zero that are length less than or equal to 3 with NA. Since NA is removed when using split(), we are left with the desired output.

    x <- c(1, 1, 2.00005, 1, 1, 0, 0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 0, 0, 1, 2, 3, 1, 3)
    
    ll <- with(rle(x == 0), {
      ifelse(x == 0 & (seq_along(x) != cumsum(lengths)[lengths <= 3 & values]), NA, x)
    })
    
    split(x, with(rle(is.na(ll)), rep(1:length(lengths), lengths) + ll * 0))
    # $`1`
    # [1] 1.00000 1.00000 2.00005 1.00000 1.00000
    #
    # $`3`
    # [1] 1 2 0 3 4
    #
    # $`5`
    # [1] 1 2 3 1 3
    

提交回复
热议问题