Announcement

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

  • Restart cumulative sum

    I am trying to generate a cumulative sum in Stata.

    The data looks as follows:

    id_marca wdate quantity indi cumquant

    A.FAMILY 2986 0 0 1371
    A.FAMILY 2987 33 4 1404
    A.FAMILY 2988 128 0 1532
    A.FAMILY 2989 74 1 1606
    A.FAMILY 2990 157 4 1763
    A.FAMILY 2991 317 9 2080
    A.FAMILY 2992 414 2 2494
    A.FAMILY 2993 305 1 2799
    A.FAMILY 2994 225 0 3024
    A.FAMILY 2995 226 1 3250
    A.FAMILY 2996 188 1 3438

    I want the cumulative sum to restart after the indicator variable "indi" is unequal to zero. This should be done for each id_marca (shown only one).

    I would appreciate the help!

  • #2
    If after means when, then consider this. Otherwise adapt to what you want.

    Code:
    bysort id_marca (wdate) : gen double wanted = quant if indi != 0 
    by id_marca : replace wanted = wanted[_n-1] + quant if missing(wanted)

    Comment


    • #3
      While I suspect Nick has correctly gleaned your intention, on the chance that you really do mean after, and not when, the code for that would be:
      Code:
      * Example generated by -dataex-. For more info, type help dataex
      clear
      input str8 id_marca int(wdate quantity) byte indi int cumquant
      "A.FAMILY" 2986   0 0 1371
      "A.FAMILY" 2987  33 4 1404
      "A.FAMILY" 2988 128 0 1532
      "A.FAMILY" 2989  74 1 1606
      "A.FAMILY" 2990 157 4 1763
      "A.FAMILY" 2991 317 9 2080
      "A.FAMILY" 2992 414 2 2494
      "A.FAMILY" 2993 305 1 2799
      "A.FAMILY" 2994 225 0 3024
      "A.FAMILY" 2995 226 1 3250
      "A.FAMILY" 2996 188 1 3438
      end
      
      by id_marca (wdate), sort: gen group = sum(indi[_n-1] != 0)
      by id_marca group (wdate), sort: gen wanted = sum(cumquant)
      In the future, when showing data examples, please use the -dataex- command to do so, as I have here. If you are running version 18, 17, 16 or a fully updated version 15.1 or 14.2, -dataex- 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.

      Comment

      Working...
      X