Ciro Mertens
Ciro Mertens

Reputation: 113

Repeat sequences where the start increases

So what I just did is this:

s1 <- seq(1, 3, by = 0.5)

rep(s1, 3)
# [1] 1.0 1.5 2.0 2.5 3.0 1.0 1.5 2.0 2.5 3.0 1.0 1.5 2.0 2.5 3.0

s2 <- seq(-4, 4, by = 2)

rep(s2, each = 3)
# [1] -4 -4 -4 -2 -2 -2  0  0  0  2  2  2  4  4  4

Now I should code something that in the end should look like this:

1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

1 to 5 5 times but the 1st number should always increase by 1. How can I do that?

Upvotes: 2

Views: 55

Answers (4)

akrun
akrun

Reputation: 887148

We can use rep

n <- 5
seq_len(n) + rep(0:4, each = n)
#[1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

Upvotes: 0

jay.sf
jay.sf

Reputation: 72901

Add to a corresponding matrix the cols.

m <- matrix(0:4, 5, 5) 
as.vector(m + col(m))
# [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101508

I guess you can try embed like below

> n <- 5
> c(embed(seq(n + 4), n)[, n:1])
 [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

Use mapply :

inds <- 1:5
c(mapply(seq, inds, inds + 4))
#[1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

Upvotes: 1

Related Questions