首页 > 解决方案 > 如何将向量拆分为相等的长度,剩余部分从父向量的第一个元素与 R 相加

问题描述

我希望 R 将向量拆分为相等长度的子向量,但如果最后一个子向量不等于其他子向量的长度,则将其与父向量的第一个元素相加。

我已经从一个问题的答案中尝试了这个,不是我想要的。

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

我想要什么作为输出

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

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

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

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

标签: rsplit

解决方案


#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

推荐阅读