创建具有固定增量的可变长度的多个序列?
Creating multiple sequences with variable lengths with fixed increment?
我想创建多个长度可变且序列之间有固定增量的序列。
喜欢:
Seq.lengths<- c(2, 4, 2, 2, 2, 4)
increment <- 3
#Output should be a list like:
c(1:2, 5:8, 11:12, 15:16, 19:20, 23:26
)
我试过“for”循环,但它对我来说不太管用。
应该有一个更聪明的解决方案,但是使用 for
循环的方法看起来像 -
Seq.lengths<- c(2, 4, 2, 2, 2, 4)
increment <- 3
result <- 1:Seq.lengths[1]
for(i in Seq.lengths[-1]) {
val <- result[length(result)] + increment
result <- c(result, val:(val + i - 1))
}
result
#[1] 1 2 5 6 7 8 11 12 15 16 19 20 23 24 25 26
如果要将输出存储在列表中 -
Seq.lengths<- c(2, 4, 2, 2, 2, 4)
increment <- 3
result <- vector('list', length(Seq.lengths))
result[[1]] <- 1:Seq.lengths[1]
for(i in 2:length(Seq.lengths)){
val <- result[[i-1]][length(result[[i-1]])] + increment
result[[i]] <- val:(val + Seq.lengths[i] - 1)
}
result
#[[1]]
#[1] 1 2
#[[2]]
#[1] 5 6 7 8
#[[3]]
#[1] 11 12
#[[4]]
#[1] 15 16
#[[5]]
#[1] 19 20
#[[6]]
#[1] 23 24 25 26
因为你有 Seq.lenths
,另一种选择可能是找到每个序列的开始
Seq.lengths <- c(2, 4, 2, 2, 2, 4)
increment <- 3
Seq.i <- seq_along(Seq.lengths[-1])
Seq.start <- cumsum(c(1, Seq.lengths[Seq.i] + (increment - 1)))
然后使用Map
和seq
得到结果
Map(function (x, y) seq(from = x, length.out = y), x = Seq.start, y = Seq.lengths)
[[1]]
[1] 1 2
[[2]]
[1] 5 6 7 8
[[3]]
[1] 11 12
[[4]]
[1] 15 16
[[5]]
[1] 19 20
[[6]]
[1] 23 24 25 26
我想创建多个长度可变且序列之间有固定增量的序列。 喜欢:
Seq.lengths<- c(2, 4, 2, 2, 2, 4)
increment <- 3
#Output should be a list like:
c(1:2, 5:8, 11:12, 15:16, 19:20, 23:26
)
我试过“for”循环,但它对我来说不太管用。
应该有一个更聪明的解决方案,但是使用 for
循环的方法看起来像 -
Seq.lengths<- c(2, 4, 2, 2, 2, 4)
increment <- 3
result <- 1:Seq.lengths[1]
for(i in Seq.lengths[-1]) {
val <- result[length(result)] + increment
result <- c(result, val:(val + i - 1))
}
result
#[1] 1 2 5 6 7 8 11 12 15 16 19 20 23 24 25 26
如果要将输出存储在列表中 -
Seq.lengths<- c(2, 4, 2, 2, 2, 4)
increment <- 3
result <- vector('list', length(Seq.lengths))
result[[1]] <- 1:Seq.lengths[1]
for(i in 2:length(Seq.lengths)){
val <- result[[i-1]][length(result[[i-1]])] + increment
result[[i]] <- val:(val + Seq.lengths[i] - 1)
}
result
#[[1]]
#[1] 1 2
#[[2]]
#[1] 5 6 7 8
#[[3]]
#[1] 11 12
#[[4]]
#[1] 15 16
#[[5]]
#[1] 19 20
#[[6]]
#[1] 23 24 25 26
因为你有 Seq.lenths
,另一种选择可能是找到每个序列的开始
Seq.lengths <- c(2, 4, 2, 2, 2, 4)
increment <- 3
Seq.i <- seq_along(Seq.lengths[-1])
Seq.start <- cumsum(c(1, Seq.lengths[Seq.i] + (increment - 1)))
然后使用Map
和seq
得到结果
Map(function (x, y) seq(from = x, length.out = y), x = Seq.start, y = Seq.lengths)
[[1]]
[1] 1 2
[[2]]
[1] 5 6 7 8
[[3]]
[1] 11 12
[[4]]
[1] 15 16
[[5]]
[1] 19 20
[[6]]
[1] 23 24 25 26