Swyler
Swyler

Reputation: 124

Create sequences with specified lengths

Is there a way to create sequences from 1 to each value of the vector a?

a <- c(1, 1, 1, 2, 1, 3, 2, 1, 1, 3)
b <- c(1, 1, 1, 1, 2, 1, 1, 2, 3, 1, 2, 1, 1, 1, 2, 3)

The values in a can be higher than 3.

Upvotes: 4

Views: 251

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52359

You can use sequence to get sequences with length described in a. sequence starts by default at 1 with an increment of 1.

sequence(a)
# [1] 1 1 1 1 2 1 1 2 3 1 2 1 1 1 2 3

all.equal(sequence(a), b)
# [1] TRUE

Upvotes: 6

Related Questions