Reputation: 168
I have a numeric vector as follows:
x <- c(1, 10, 11, 15, 16, 21, 22, 26, 27, 31,
32, 36, 37, 41, 42, 46, 47, 51, 52, 56)
I want to create a list of numeric sequences that runs between the first and second element, third and fourth element, fifth and sixth element and so on.
The expected outcome is the following list:
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
[[2]]
[1] 11 12 13 14 15
[[3]]
[1] 16 17 18 19 20 21
[[4]]
[1] 22 23 24 25 26
[[5]]
[1] 27 28 29 30 31
[[6]]
[1] 32 33 34 35 36
[[7]]
[1] 37 38 39 40 41
[[8]]
[1] 42 43 44 45 46
[[9]]
[1] 47 48 49 50 51
[[10]]
[1] 52 53 54 55 56
I would prefer a solution in base R.
Upvotes: 3
Views: 301
Reputation: 887851
We can use map2
library(purrr)
map2(x[c(TRUE, FALSE)], x[c(FALSE, TRUE)], `:`)
Upvotes: 2
Reputation: 270195
Apply seq to the odd and even positioned values of x
:
Map(seq, x[c(TRUE, FALSE)], x[c(FALSE, TRUE)])
This can be written even more compactly like this:
Map(seq, x[!0:1], x[!1:0])
Upvotes: 6