Split vector separated by n zeros into different group

后端 未结 5 1228
情歌与酒
情歌与酒 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 23:08

    Here is a method with rle, split, and lapply

    # get RLE
    temp <- rle(x)
    # replace values with grouping variables
    temp$values <- cumsum(temp$values == 0 & temp$lengths > 2)
    
    # split on group and lapply through, dropping 0s at beginning which are start of each group
    lapply(split(x, inverse.rle(temp)), function(y) y[cummax(y) > 0])
    $`0`
    [1] 1.00000 1.00000 2.00005 1.00000 1.00000
    
    $`1`
    [1] 1 2 0 3 4
    
    $`2`
    [1] 1 2 3 1 3
    

    A second method without lapply is as follows

    # get RLE
    temp <- rle(x)
    # get positions of 0s that force grouping
    changes <- which(temp$values == 0 & temp$lengths > 2)
    # get group indicators
    temp$values <- cumsum(temp$values == 0 & temp$lengths > 2)
    # make 0s a new group
    temp$values[changes] <- max(temp$values) + 1L
    
    # create list
    split(x, inverse.rle(temp))
    $`0`
    [1] 1.00000 1.00000 2.00005 1.00000 1.00000
    
    $`1`
    [1] 1 2 0 3 4
    
    $`2`
    [1] 1 2 3 1 3
    
    $`3`
    [1] 0 0 0 0 0 0 0 0
    

    Finally, you'd just drop the last list item, like head(split(x, inverse.rle(temp)), -1).

提交回复
热议问题