Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of number sequences from elements of a vector in R

Tags:

r

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.

like image 398
GAURAV DIWAN Avatar asked Dec 04 '25 03:12

GAURAV DIWAN


1 Answers

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])
like image 148
G. Grothendieck Avatar answered Dec 05 '25 17:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!