Split vector based on block length vector

I have a binary number vector. I know the sequential length of each group of objects; How can I split based on this information (without a loop)?

x = c("1","0","1","0","0","0","0","0","1") .length = c(group1 = 2,group2=4, group3=3) 

x is the binary number vector that I need to split. .length is the information I give. .length essentially tells me that the first group has 2 elements, and they are the first two elements of 1,0 . The second group has elements 4 and contains 4 numbers that follow the numbers of group 1, 1,0,0,0 , etc.

Is there a way to split this and return the split item to the list?

The ugly way is to track the current cumsum through a for loop, but I'm looking for a more elegant way, if any.

+6
source share
2 answers

You can use rep to set the split-by variable using 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 want to take group names with you to the splitting list, you can change the 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" 
+9
source

Another variant:

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

to get group names

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

Source: https://habr.com/ru/post/980452/


All Articles