Splitting vector based on vector of chunk-lengths

前端 未结 2 1403
眼角桃花
眼角桃花 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:39

    You can use rep to set up the split-by variable, the use split

    x = c("1","0","1","0","0","0","0","0","1")
    .length = c(group1 = 2,group2=4, group3=3)
    
    split(x, rep.int(seq_along(.length), .length))
    # $`1`
    # [1] "1" "0"
    #
    # $`2`
    # [1] "1" "0" "0" "0"
    #
    # $`3`
    # [1] "0" "0" "1"
    

    If you wanted to take the group names with you to the split list, you can change rep to replicate the names

    split(x, rep.int(names(.length), .length))
    # $group1
    # [1] "1" "0"
    #
    # $group2
    # [1] "1" "0" "0" "0"
    #
    # $group3
    # [1] "0" "0" "1"
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题