Split a vector into equal length of subvectors with a leftover as the last subvector when the length is not divisible with its subset [duplicate]

这一生的挚爱 提交于 2020-04-12 07:28:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!