Daniel James
Daniel James

Reputation: 1433

How do I Split a vector to equal length with the left over adding up from the first element(s) of parent vector with R

I want R to split a vector to subvector of equal length but if the last subvector is not equal to the length of other subvectors to add it up with the first element(s) of the parent vector.

I have tried this from an answer to a question Here which is not what I desire.

ts <- 1:11 
bs <- 3 
nb <- ceiling(length(ts) / bs)

split(ts, rep(1:nb, each=bs, length.out = length(ts)))

#$`1`
#[1] 1 2 3

#$`2`
#[1] 4 5 6

#$`3`
#[1] 7 8 9

#$`4`
#[1] 10 11

What I want as output

#$`1`
#[1] 1 2 3

#$`2`
#[1] 4 5 6

#$`3`
#[1] 7 8 9

#$`4`
#[1] 10 11 1

Upvotes: 0

Views: 68

Answers (1)

d.b
d.b

Reputation: 32548

#Extend the `ts` to have a total length of `bs * nb`
split(rep(ts, length.out = nb * bs), rep(1:nb, each = bs))
#OR use modular arithmetic
split(ts[((sequence(nb * bs) - 1) %% length(ts)) + 1], rep(1:nb, each = bs))
#$`1`
#[1] 1 2 3

#$`2`
#[1] 4 5 6

#$`3`
#[1] 7 8 9

#$`4`
#[1] 10 11  1

Upvotes: 1

Related Questions