Announcement

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

  • Equivalent of total() for Product of observations

    Dear Statalisters,

    This is my first post here.

    I am looking for a way to generate the product of the observations within a variable so that I have a separate column of identical values, each being the product of all the observations of the said variable, like egen total() does with the sum.

    To make an example, if X is my variable, I would have X= (x1, x2, x3, x4) and I would like to have ProdX = (x1*x2*x3*x4,...)

    To the best of my knowledge (that may be very poor, since it's not been long that I encountered this issue) I have not found an answer in a previous post. The next best thing I found was the prod plugin, but it seems to me it's more an analogous to the sum option rather than total.

    I sincerely hope I was clear enough.

    Thank you for any contribution.

    Tommaso

  • #2
    Here are two methods. The second isn't valid if any values are negative. Naturally any zeros annihilate products any way.

    Code:
    sysuse auto, clear
    
    bysort foreign : gen double product = length[1]
    by foreign : replace product = product[_n-1] * length if _n > 1
    by foreign : replace product = product[_N]
     
    by foreign : gen double product2 = sum(log(length))
    by foreign : replace product2 = exp(product2[_N])
    
    tabdisp foreign, c(product*)
    
    ----------------------------------
     Car type |    product    product2
    ----------+-----------------------
     Domestic |  1.24e+119   1.24e+119
      Foreign |  9.070e+48   9.070e+48
    ----------------------------------

    Comment


    • #3
      Dear Mr. Cox,

      Thank you. I shall apply this method to my problem right away.

      Thanks for the swift answer.

      Tommaso Bechini

      Comment

      Working...
      X