Daniel James
Daniel James

Reputation: 1433

How do I split a vector to subvectors with a specified subvector lengths in R

I want R to split a vector to subvectors with the lengths of each subvectors being specified.

If I have a vector ts which ranges from 1 to 30, I like to split it to subvectors with the length of the subvectors to be 4 4 4 4 2 2 2 2 4 2

ts<-1:30
t<-c(4 4 4 4 2 2 2 2 4 2)
split(ts, each=t) # divides the series into blocks

** Result that I want**

# 1 2 3 4
#5 6 7 8
#9 10 11 12
#13 14 15 16
#17 18
#19 20
#20 22
#23 24
#25 26 27 28
#29 30

Upvotes: 0

Views: 617

Answers (1)

akrun
akrun

Reputation: 887048

We create a grouping index with rep using the 't' vector and split the 'ts' vector

split(ts, rep(seq_along(t), t))
#$`1`
#[1] 1 2 3 4

#$`2`
#[1] 5 6 7 8

#$`3`
#[1]  9 10 11 12

#$`4`
#[1] 13 14 15 16

#$`5`
#[1] 17 18

#$`6`
#[1] 19 20

#$`7`
#[1] 21 22

#$`8`
#[1] 23 24

#$`9`
#[1] 25 26 27 28

#$`10`
#[1] 29 30

data

ts <- 1:30
t <- c(4, 4, 4, 4, 2, 2, 2, 2, 4, 2)

NOTE: Both ts and t are function names. it is better to specify object names with a different name

Upvotes: 1

Related Questions