Announcement

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

  • Compute the Partial sum of a Variable within Group in Stata?

    I have a small dataset as follows,
    clear
    input schid person_id math_score
    1 1 89
    1 11 67
    1 12 99
    2 1 100
    2 11 88
    2 12 85
    2 13 95
    end
    I want to create a new variable called partial_sum, which should be equal to the sum of the values of math_score except for the 1st observation within schid. For example, when schid=1, the partial_sum=67+99=176; when schid=2, the partial_sum=88+85+95=268 Can someone help me with the Stata code? Thank you!

  • #2
    Jason:
    do you mean something along the following lines?
    Code:
    . bysort schid: egen wanted=total( math_score) if _n>1
    
    
    . list
    
         +--------------------------------------+
         | schid   person~d   math_s~e   wanted |
         |--------------------------------------|
      1. |     1          1         89        . |
      2. |     1         11         67      166 |
      3. |     1         12         99      166 |
      4. |     2          1        100        . |
      5. |     2         11         88      268 |
         |--------------------------------------|
      6. |     2         12         85      268 |
      7. |     2         13         95      268 |
         +--------------------------------------+
    
    .
    Kind regards,
    Carlo
    (Stata 19.0)

    Comment


    • #3
      Thank you! If I want the missing value is replaced by the computed sum, could you please help me with your code?

      Comment


      • #4
        Jason:
        Code:
        . bysort schid: replace wanted=wanted[2] if wanted==.
        
        
        . list
        
             +--------------------------------------+
             | schid   person~d   math_s~e   wanted |
             |--------------------------------------|
          1. |     1          1         89      166 |
          2. |     1         11         67      166 |
          3. |     1         12         99      166 |
          4. |     2          1        100      268 |
          5. |     2         11         88      268 |
             |--------------------------------------|
          6. |     2         12         85      268 |
          7. |     2         13         95      268 |
             +--------------------------------------+
        
        .
        Kind regards,
        Carlo
        (Stata 19.0)

        Comment


        • #5
          Thank you!

          Comment

          Working...
          X