Create a vector using rep() and seq()

1.4k views Asked by At

How to create a vector sequence of:

2 3 4 5 6 7 8 3 4 5 6 7 8 4 5 6 7 8 5 6 7 8 6 7 8 7 8

I tried to use:

2:8+rep(0:6,each=6)

but the result is:

2 3 4 5 6 7 8 3 4 5 6 7 8 9 4 5 6 7 8 9 10 .... 12 13 14

Please help. Thanks.

3

There are 3 answers

2
moodymudskipper On

you could do this:

library(purrr)
unlist(map(2:7, ~.x:8))

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

and a little function in base R:

funky_vec <- function(from,to){unlist(sapply(from:(to-1),`:`,to))}
funky_vec(2,8)
# [1] 2 3 4 5 6 7 8 3 4 5 6 7 8 4 5 6 7 8 5 6 7 8 6 7 8 7 8
0
Jordan On

This should accomplish what you're looking for:

x = 2
VecSeq = c(x:8)

while (x < 7) {
    x = x + 1
    calc = c(x:8)
    VecSeq = c(VecSeq, calc)
}

VecSeq # Your desired vector
0
Maël On

This is made really easy with sequence (since R 4.0.0):

sequence(7:2, 2:7)
#  [1] 2 3 4 5 6 7 8 3 4 5 6 7 8 4 5 6 7 8 5 6 7 8 6 7 8 7 8