Splitting vector based on vector of chunk-lengths

前端 未结 2 1414
眼角桃花
眼角桃花 2020-12-19 07:24

I\'ve got a vector of binary numbers. I know the consecutive length of each group of objects; how can I split based on that information (without for loop)?

x         


        
2条回答
  •  情歌与酒
    2020-12-19 07:47

    Another option is

    split(x,cumsum(sequence(.length)==1))
    #$`1`
    #[1] "1" "0"
    
    #$`2`
    #[1] "1" "0" "0" "0"
    
    #$`3`
    #[1] "0" "0" "1"
    

    to get the group names

    split(x, sub('.$', '', names(sequence(.length))))
    #$group1
    #[1] "1" "0"
    
    #$group2
    #[1] "1" "0" "0" "0"
    
    #$group3
    #[1] "0" "0" "1"
    

提交回复
热议问题