0

I would like to create multiple sequences with variable lengths and a fixed increment between those sequences. Like:

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
)

I´ve tried "for" loops but, it doesn´t quite work for me.

2 Answers 2

0

There should be a smarter solution to this but an approach with for loop would look like -

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

If you want to store the output in a list -

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
Sign up to request clarification or add additional context in comments.

1 Comment

That was completely sufficient. I was also thinking about using ´´´apply´´´ in some sort of way. Maybe that could improve the process?
0

As you have Seq.lenths, another option could be to find the start of each sequence

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)))

Then use Map and seq to get result

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.