Search code examples
rlistsegment

Segmenting list in R


I just recently started learning R, so please excuse the basic question.

I have a list of the form:

  X1  X2  X3
1  1 214   1
2  1 213 813
3  2 216  21
4  2 210   1
5  2 218 423
6  3 209  18
...

And I would like to segment the list by indexes in X1:

  X1  X2  X3
1  1 214   1
2  1 213 813

  X1  X2  X3
1  2 216  21
2  2 210   1
3  2 218 423

  X1  X2  X3
1  3 209  18
...

The number of rows per index varies.

I believe I need to create a function on the X1 column, but I don't know how to return several lists as a result.

Any advice would be much appreciated!


Solution

  • You are looking for the function split.

    Assuming your data.frame is called DD

    split(DD, DD$X1)
    $`1`
      X1  X2  X3
    1  1 214   1
    2  1 213 813
    
    $`2`
      X1  X2  X3
    3  2 216  21
    4  2 210   1
    5  2 218 423
    
    $`3`
      X1  X2 X3
    6  3 209 18