Announcement

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

  • How to create a sequence within a group?

    Hello,

    I appreciate your help on this.

    I have patient level data with and ID and subID. I want to generate the sequence (such as 1,2,3,4...) for the subID group within the ID.

    e.g., this is how my data looks like
    ID SubID
    A x
    A x
    A y
    A y
    B m
    B m
    B n
    B n
    B o
    B o

    I want the sequence to be generated as follows
    ID SubID Sequence
    A x 1
    A x 1
    A y 2
    A y 2
    B m 1
    B m 1
    B n 2
    B n 2
    B o 3
    B o 3

    appreciate your support very much

  • #2
    Please follow https://www.statalist.org/forums/help#stata and use dataex to show examples.


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str1(D SubId)
    "A" "x"
    "A" "x"
    "A" "y"
    "A" "y"
    "B" "m"
    "B" "m"
    "B" "n"
    "B" "n"
    "B" "o"
    "B" "o"
    end
    
    bysort D (SubId): gen wanted = sum(SubId != SubId[_n-1])
    
    list , sepby(D SubId)
    
         +--------------------+
         | D   SubId   wanted |
         |--------------------|
      1. | A       x        1 |
      2. | A       x        1 |
         |--------------------|
      3. | A       y        2 |
      4. | A       y        2 |
         |--------------------|
      5. | B       m        1 |
      6. | B       m        1 |
         |--------------------|
      7. | B       n        2 |
      8. | B       n        2 |
         |--------------------|
      9. | B       o        3 |
     10. | B       o        3 |
         +--------------------+
    Code:
    
    

    Comment


    • #3
      Thank you Nick for the response, it worked

      Comment

      Working...
      X