Announcement

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

  • how to store sum over product of two variables in local

    Dear All,

    I guess this is a trivial question, but I simply didnt know how to search for the answer (I tried but failed).

    I have a standard dataset with three variables ID Y X
    The dataset has 100 observations.
    I want to create two locals
    1) the sum of all products Y*X,
    ....i.e. if I wanted to create it as a variable it would be
    gen product=Y*X
    egen sum_product=sum(product)

    2)the average of that sum

    How do I create these local directly (without first having to generate a variable)

    Many thanks

    Darjusch


  • #2
    Here is one way using Mata:

    Code:
    sysuse auto
    mata : mysum =sum( st_data(., ("price")):* st_data(., ("weight")))
    mata : mymean=mean( st_data(., ("price")):* st_data(., ("weight")))
    mata : st_numscalar("mysum", mysum)
    mata : st_numscalar("mymean", mymean)
    local mean = scalar(mymean)
    disp "`mean'"
    local sum = scalar(mysum)
    disp "`sum'"

    Comment


    • #3
      I think that for your second request, you intended to say average of the product, didn't you?

      In addition to Scott's Mata approach, if you want to stay in Stata, then try
      Code:
      scalar define sum = 0
      forvalues i = 1/`=_N' {
          scalar define sum = sum + X[`i'] * Y[`i']
      }
      
      display in smcl as text "Sum = " %7.3f sum
      display in smcl as text "Average = " %06.4f sum / _N
      I don't know why you don't like your own approach, but if you have some kind of problem creating new permanent variables in your dataset and don't want to loop over observations, then you could create a temporary variable inside an ado-file that leaves the sum and average behind in returned scalars.
      Code:
      program define sum_product
          version 13.1
          syntax varlist(min=2 max=2 numeric)
      
          gettoken left right : varlist
          tempvar product
          generate double `product' = `left' * `right'
          summarize `product', meanonly
      end
      
      display in smcl as text "Sum = " %7.3f r(sum)
      display in smcl as text "Average = " %06.4f r(mean)

      Comment

      Working...
      X