r - 如何将向量拆分为相等的长度,剩余部分从父向量的第一个元素与 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
解决方案
#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
推荐阅读
- r - 当我尝试使用 bookdown::publish_book() 发布书籍时出错
- c# - 如果在 C# 中是密封的、继承的或抽象的,如何知道是否可以实例化一个类或接口?
- python - 烧瓶用 python dict 中的值填充表单
- php - 如何使用 PHP 和 mysql 生成具有静态内容的基本 HTML 页面?
- sql - SQL - 多个描述 - 返回第一个值
- android - 在 Android Studio 上运行终端命令
- c - 如何从 .dat 文件中提取资源文件?
- javascript - React:在状态下,我将如何更新某个索引处的嵌套对象?
- uikit - 试剂,UIkit 下拉使用
- java - 循环不断打印每个增加的结果