dfrankow
dfrankow

Reputation: 21357

Splitting data in R in order

Here is splitting a range into 3 sections in R:

> a=1:35
> split(a, 1:3)
$`1`
 [1]  1  4  7 10 13 16 19 22 25 28 31 34

$`2`
 [1]  2  5  8 11 14 17 20 23 26 29 32 35

$`3`
 [1]  3  6  9 12 15 18 21 24 27 30 33

However, I wanted it split into 1:12, 13:24, 25:35 instead. How do I get it not to re-order?

Upvotes: 0

Views: 81

Answers (1)

josliber
josliber

Reputation: 44299

The groupings you passed are 1, 2, 3, 1, 2, 3, ... but you actually wanted 1, 1, 1, ..., 1, 2, 2, 2, ..., 2, 3, 3, 3, ..., 3.

a = 1:35
groups = c(rep(1, 12), rep(2, 12), rep(3, 11))
split(a, groups)
$`1`
 [1]  1  2  3  4  5  6  7  8  9 10 11 12

$`2`
 [1] 13 14 15 16 17 18 19 20 21 22 23 24

$`3`
 [1] 25 26 27 28 29 30 31 32 33 34 35

Upvotes: 1

Related Questions