'Create a vector using rep() and seq()
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.
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jordan |
Solution 2 | ah bon |
Solution 3 | Maël |