Announcement

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

  • Cumulative product over a variable

    Hi

    I am trying to calculate the cumulative product of a variable (var1) and get the result in a new variable (product). Example:

    var1 product
    1 1
    3 3
    5 15
    7 105

    Any ideas on how to best implement this in Stata 15.1? Thanks!

  • #2
    Code:
    clear*
    set obs 4
    gen var1 = 2*_n - 1
    list, noobs clean
    
    gen product = 1 in 1
    replace product = product[_n-1]*var1 in 2/L
    
    list, noobs clean

    Comment


    • #3
      Isabel:
      as an aside to Clyde's helpful reply, I recall an old trick proposed by Nick that saved my head from an urgent TC scan after having banged it against the wall all the afternoon long some years ago:
      Code:
      . set obs 10
      
      . g A=_n
      
      . g B=sum(ln(A))
      
      . replace B=exp(B)
      Kind regards,
      Carlo
      (Stata 18.0 SE)

      Comment


      • #4
        Thank you Clyde, I acutally finally got to the very same solution just a few seconds ago.

        Comment


        • #5
          It does no harm to insist that products go in double variables.

          Comment

          Working...
          X