Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • grouping and count

    The original data value is shown as x, first of all, it is hoped that the same value can be next to different stages, as shown in x1; secondly, the number of each stage is expected to be counted, as shown in x2.I'm looking forward to your reply.Thanks!!!
    x x1 x2
    0 1 1
    0 1 2
    0 1 3
    0 1 4
    1 2 1
    1 2 2
    1 2 3
    1 2 4
    0 3 1
    0 3 2
    0 3 3
    1 4 1
    0 5 1
    Last edited by Xulei Liu; 11 May 2022, 10:40.

  • #2
    Code:
    generate seq = _n
    generate x1 = sum(x!=x[_n-1])
    bysort x1 (seq): generate x2 = _n
    sort seq
    drop seq
    list, sepby(x1)
    Code:
    . list, sepby(x1)
    
         +-------------+
         | x   x1   x2 |
         |-------------|
      1. | 0    1    1 |
      2. | 0    1    2 |
      3. | 0    1    3 |
      4. | 0    1    4 |
         |-------------|
      5. | 1    2    1 |
      6. | 1    2    2 |
      7. | 1    2    3 |
      8. | 1    2    4 |
         |-------------|
      9. | 0    3    1 |
     10. | 0    3    2 |
     11. | 0    3    3 |
         |-------------|
     12. | 1    4    1 |
         |-------------|
     13. | 0    5    1 |
         +-------------+

    Comment


    • #3
      Here's another way to think about it in addition to @William Lisowski's fine answer.

      Given a time (time-like, order or sequence) variable and a tsset this falls under the heading of tsspell from SSC. tsspell is a good search term for this forum.


      Code:
      * Example generated by -dataex-. For more info, type help dataex
      clear
      input float x
      0
      0
      0
      0
      1
      1
      1
      1
      0
      0
      0
      1
      0
      end
      . 
      . gen t = _n 
      
      . tsset t 
      
      Time variable: t, 1 to 13
              Delta: 1 unit
      
      . tsspell x 
      
      . 
      . list, sepby(_spell)
      
           +-------------------------------+
           | x    t   _spell   _seq   _end |
           |-------------------------------|
        1. | 0    1        1      1      0 |
        2. | 0    2        1      2      0 |
        3. | 0    3        1      3      0 |
        4. | 0    4        1      4      1 |
           |-------------------------------|
        5. | 1    5        2      1      0 |
        6. | 1    6        2      2      0 |
        7. | 1    7        2      3      0 |
        8. | 1    8        2      4      1 |
           |-------------------------------|
        9. | 0    9        3      1      0 |
       10. | 0   10        3      2      0 |
       11. | 0   11        3      3      1 |
           |-------------------------------|
       12. | 1   12        4      1      1 |
           |-------------------------------|
       13. | 0   13        5      1      1 |
           +-------------------------------+

      Comment

      Working...
      X