问题
I want to split a vector into some same length of subvector but when it does not have a multiple of the vector, it should make other subvectors equal length but the last be shorter.
This question is different from Split a vector into chunks in R as I want the shorter subvector to come last and the subvector length should not be greater than specified.
I have a set of values (say 11 values) in a vector. I want to divide it into subsets of known size. If I want to divide it into 4 sets of size 3 then I can use.
But my problem is when I don't have matching multiples of sizes. Say I want to divide the vector into sets of 3. So there will be 4 sets but the last set will be short
ts <- 1:11 # the parent vector
bs <- 3 # lenght of subvector
nb <- length(ts) / bs # number of subvector
blk <- split(ts, rep(1:nb, each=bs)) # the subvectors which gives the below error:
Warning message:
In split.default(ts, rep(1:nb, each = bs)) :
data length is not a multiple of split variable
** What I want:**
#$`1`
#[1] 1 2 3
#$`2`
#[1] 4 5 6
#$`3`
#[1] 7 8 9
#$`4`
#[1] 10 11
回答1:
We can use ceiling
to round nb
and length.out
argument in rep
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
来源:https://stackoverflow.com/questions/58046514/split-a-vector-into-equal-length-of-subvectors-with-a-leftover-as-the-last-subve