Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

split data and re-arrange values based on split number

$
0
0

I have this data:

      row col
 [1,]   1   1
 [2,]   7   1
 [3,]   2   2
 [4,]   7   2
 [5,]  18   2
 [6,]   3   3
 [7,]   4   4
 [8,]   5   5
 [9,]  19   5
[10,]   6   6
[11,]   1   7
[12,]   2   7
[13,]   7   7
[14,]  18   7
[15,]   8   8
[16,]   9   9
[17,]  10  10
[18,]  11  11
[19,]  12  12
[20,]  13  13
[21,]  18  13
[22,]  14  14
[23,]  15  15
[24,]  16  16
[25,]  17  17
[26,]   2  18
[27,]   7  18
[28,]  13  18
[29,]  18  18
[30,]   5  19
[31,]  19  19
[32,]  20  20

I would like to split it based on some condition on the ordering. I can split it using:

split(m1[, 'row'], m1[, 'col'])

Which gives me this output:

$`1`
[1] 1 7

$`2`
[1]  2  7 18

$`3`
[1] 3

$`4`
[1] 4

$`5`
[1]  5 19

$`6`
[1] 6

$`7`
[1]  1  2  7 18

$`8`
[1] 8

$`9`
[1] 9

$`10`
[1] 10

$`11`
[1] 11

$`12`
[1] 12

$`13`
[1] 13 18

$`14`
[1] 14

$`15`
[1] 15

$`16`
[1] 16

$`17`
[1] 17

$`18`
[1]  2  7 13 18

$`19`
[1]  5 19

$`20`
[1] 20

However I would like to keep some ordering. Splits 1 - 6 are correct since the first value in split 1 is 1 (the second being 7). The first value in split 2 is 2 (the second is 7 and third is 18). The pattern continues until it breaks on split 7. I would like split 7 to look like:

 $`7`
[1]  7  1  2  18

Split 8 to 17 are all fine also. Since the first number corresponds to the split number. I woulld like split 18 and 19 to look like:

$`18`
[1]  18  2  7 13

$`19`
[1]  19  5

How can I split the data using this struture?

Data:

m1 <- structure(c(1L, 7L, 2L, 7L, 18L, 3L, 4L, 5L, 19L, 6L, 1L, 2L, 
7L, 18L, 8L, 9L, 10L, 11L, 12L, 13L, 18L, 14L, 15L, 16L, 17L, 
2L, 7L, 13L, 18L, 5L, 19L, 20L, 1L, 1L, 2L, 2L, 2L, 3L, 4L, 5L, 
5L, 6L, 7L, 7L, 7L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 13L, 14L, 
15L, 16L, 17L, 18L, 18L, 18L, 18L, 19L, 19L, 20L), .Dim = c(32L, 
2L), .Dimnames = list(NULL, c("row", "col")))

Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>