Announcement

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

  • cumulative sum that restarts at 0, if observe "0" in the original column.

    Hi, I have a simple question. I would like to have a cumulate sum that restarts if observing 0 in the original column. I have a simple example. Is there an easy way to do this? I tried several ways to do this, but couldn't figure out a way to do this.

    ex)x is a column of original data and y is the desired outcome

    x y
    1 1
    1 2
    1 3
    1 4
    1 5
    0 0
    1 1
    1 2
    1 3
    1 4


  • #2
    Code:
    gen long obs_no = _n
    expand 2 in 1
    sort obs_no
    replace x = 0 in 1
    gen byte spell = (x == 0)
    replace spell = sum(spell)
    by spell (obs_no), sort: gen y = _n - 1
    drop in 1
    In the future, when showing data examples, please use the -dataex- command to do so, as I have done here. If you are running version 15.1 or a fully updated version 14.2, it is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    When asking for help with code, always show example data. When showing example data, always use -dataex-.


    Comment


    • #3
      Clyde gives excellent advice as always. This is another way to get your results with your example.

      Code:
      clear 
      input x y
      1 1
      1 2
      1 3
      1 4
      1 5
      0 0
      1 1
      1 2
      1 3
      1 4
      end 
      
      gen wanted = cond(_n == 1 | x == 0, x, .) 
      replace wanted = wanted[_n-1] + x if missing(wanted) 
      
      list 
      
           +----------------+
           | x   y   wanted |
           |----------------|
        1. | 1   1        1 |
        2. | 1   2        2 |
        3. | 1   3        3 |
        4. | 1   4        4 |
        5. | 1   5        5 |
           |----------------|
        6. | 0   0        0 |
        7. | 1   1        1 |
        8. | 1   2        2 |
        9. | 1   3        3 |
       10. | 1   4        4 |
           +----------------+

      Comment


      • #4
        Thank you, Clyde and Nick, for helping me out. And next time, I will use -dataex- for example.

        Comment

        Working...
        X