user3664020
user3664020

Reputation: 3020

Create a sequence of sequences of different lengths

I have to create a sequence of large number (> 10,000) of sequences of different lengths. I only know the lengths of these sequences in a vector form.

length_v <- c(2,3,4,4,2,6,11,75...................)

Each sequence starts from 1 and moves forward in steps of 1. And in the final sequence (combined one), each sequence has to appear one after the other, they can't be jumbled up.

A small demonstrating example is below:

I have say 4 sequences of length 2, 3, 4, 6 respectively.

s1 <- seq(1, 2)  # 1,2
s2 <- seq(1, 3)  # 1,2,3
s3 <- seq(1, 4)  # 1,2,3,4
s4 <- seq(1, 6)  # 1,2,3,4,5,6 

Final sequence will be

final <- c(s1,s2,s3,s4) **# the order has to be this only. No compromise here.**

I can't do this with > 10,000 sequences which would be very inefficient. Is there any simpler way of doing this?

Upvotes: 5

Views: 2476

Answers (2)

akrun
akrun

Reputation: 886938

We can use sequence

sequence(length_v)
#[1] 1 2 1 2 3 1 2 3 4 1 2 3 4 5 6

data

length_v <- c(2,3,4,6)

Upvotes: 7

jogo
jogo

Reputation: 12559

example:

unlist(sapply(c(2,3,4,6), seq, from=1))

so for you it will be:

unlist(sapply(length_v, seq, from=1))

Upvotes: 4

Related Questions