You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中按指定元素数量拆分向量为子向量?

解决方案:按指定长度拆分R向量

方法一:使用split()函数(简洁高效)

通过生成分组因子,将原向量按指定长度拆分,最后将拆分结果赋值给目标变量:

data_controllo<- c("2018-09-24 UTC","2018-10-22 UTC", "2018-11-21 UTC", "2018-12-19 UTC", "2019-01-30 UTC", "2019-03-01 UTC", "2019-03-27 UTC", "2019-04-29 UTC","2019-05-31 UTC", "2019-07-30 UTC", "2019-08-28 UTC", "2019-09-26 UTC", "2019-10-22 UTC","2019-11-20 UTC","2019-12-16 UTC", "2020-01-21 UTC", "2020-02-17 UTC", "2020-04-21 UTC", "2020-05-19 UTC", "2020-06-16 UTC", "2020-07-14 UTC", "2020-08-18 UTC", "2020-09-16 UTC", "2020-10-13 UTC", "2020-12-09 UTC", "2021-01-12 UTC", "2021-02-12 UTC", "2021-03-11 UTC", "2021-04-09 UTC", "2021-05-10 UTC")

elements_perVector <- c(17, 5, 1, 5, 2)

# 生成对应长度的分组标签
groups <- rep(seq_along(elements_perVector), elements_perVector)
# 拆分向量为列表
split_list <- split(data_controllo, groups)

# 将列表元素赋值给目标子向量
subvector1 <- split_list[[1]]
subvector2 <- split_list[[2]]
subvector3 <- split_list[[3]]
subvector4 <- split_list[[4]]
subvector5 <- split_list[[5]]

执行后,直接调用subvector1至subvector5即可得到你需要的结果。

方法二:手动计算索引拆分(直观易懂)

通过计算每个子向量的起始/结束位置,直接截取原向量的对应片段:

data_controllo<- c("2018-09-24 UTC","2018-10-22 UTC", "2018-11-21 UTC", "2018-12-19 UTC", "2019-01-30 UTC", "2019-03-01 UTC", "2019-03-27 UTC", "2019-04-29 UTC","2019-05-31 UTC", "2019-07-30 UTC", "2019-08-28 UTC", "2019-09-26 UTC", "2019-10-22 UTC","2019-11-20 UTC","2019-12-16 UTC", "2020-01-21 UTC", "2020-02-17 UTC", "2020-04-21 UTC", "2020-05-19 UTC", "2020-06-16 UTC", "2020-07-14 UTC", "2020-08-18 UTC", "2020-09-16 UTC", "2020-10-13 UTC", "2020-12-09 UTC", "2021-01-12 UTC", "2021-02-12 UTC", "2021-03-11 UTC", "2021-04-09 UTC", "2021-05-10 UTC")

elements_perVector <- c(17, 5, 1, 5, 2)

# 计算每个子向量的起始位置
start_pos <- c(1, cumsum(elements_perVector)[-length(elements_perVector)] + 1)
# 计算每个子向量的结束位置
end_pos <- cumsum(elements_perVector)

# 截取生成子向量
subvector1 <- data_controllo[start_pos[1]:end_pos[1]]
subvector2 <- data_controllo[start_pos[2]:end_pos[2]]
subvector3 <- data_controllo[start_pos[3]:end_pos[3]]
subvector4 <- data_controllo[start_pos[4]:end_pos[4]]
subvector5 <- data_controllo[start_pos[5]:end_pos[5]]

说明

两种方法都能保证原向量的元素顺序不变,且完全匹配你指定的拆分长度。方法一更适合批量处理,方法二的索引计算逻辑更直观,可根据需求选择。

内容的提问来源于stack exchange,提问作者Andrea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 21:12:12