Sandra Ross Sandra Ross - 2 months ago 6
R Question

Generate 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 with `rep()` and `seq()`

I'm having a problem in creating the vector

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


with
rep()
and
seq()
. Could anyone be able to give me a hint?

Answer

We can use

rep(1:5, times = 5) + rep(0:4, each = 5)
# [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

or simpler (as R will recycle 1:5 automatically):

rep(0:4, each = 5) + 1:5
# [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

Is there a way to do that with the command seq?

1:5 is just seq(1,5), while 0:4 is seq(0,4).


Ah, for those who are interested in, we can also use outer:

as.numeric(outer(1:5, 0:4, "+"))

The initial call to outer generates this matrix:

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    2    3    4    5    6
#[3,]    3    4    5    6    7
#[4,]    4    5    6    7    8
#[5,]    5    6    7    8    9

then we use as.numeric to flatten it.