R语言如何生成可变长度且序列间固定增量的多组序列
解决方案
需求说明
给定存储每段序列长度的向量Seq.lengths、序列之间的固定间隔值increment,生成拼接后的整数序列:每段按指定长度生成,两段之间跳过increment个整数再生成下一段。
方法1:for循环实现
你之前用循环没得到正确结果大概率是起始位置更新逻辑出错,以下是可直接运行的正确实现:
Seq.lengths <- c(2, 4, 2, 2, 2, 4) increment <- 3 result <- c() current_start <- 1 for (seg_len in Seq.lengths) { # 生成本段序列 current_seg <- current_start:(current_start + seg_len -1) result <- c(result, current_seg) # 计算下一段起始位置:本段最后一个值 + 1 + 固定间隔 current_start <- current_seg[length(current_seg)] + 1 + increment } print(result) # 输出:[1] 1 2 5 6 7 8 11 12 15 16 19 20 23 24 25 26
方法2:向量化实现(更高性能)
如果处理的序列很长,用向量化运算比循环效率更高,实现如下:
Seq.lengths <- c(2, 4, 2, 2, 2, 4) increment <- 3 # 计算每段的起始位置 seg_starts <- c(1, cumsum(Seq.lengths + increment)[-length(Seq.lengths)] + 1) # 计算每段的结束位置 seg_ends <- seg_starts + Seq.lengths - 1 # 拼接所有序列 result <- unlist(Map(seq, from = seg_starts, to = seg_ends)) print(result)
两种方法输出的结果都和你给出的示例要求完全一致。
内容的提问来源于stack exchange,提问作者Fabian.m
相关产品推荐
相关产品推荐

