Announcement

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

  • Generating average using egen

    Hi, all. I am trying to generate a new variable by calculating averages by subgroup. To do this, I use the following command:

    sort Group Period
    bysort Group Period: egen mcost = mean(Cost)


    My problem is that the variable Cost contains zeros, and I would like to exclude those zeros from the calculations. For example, I would like the mean of 0, 0, 2, 2 to be 2 and not 1. I tried to add if Cost != 0 at the end but I received values only where Cost is positive. Any suggestions? Thanks in advance.

  • #2
    Code:
    bysort Group Period : egen mcost = mean(cond(Cost > 0, Cost, .))
    See also https://journals.sagepub.com/doi/pdf...867X1101100210 Section 9

    Note that with your first solution, there is a fix within reach:

    Code:
    bysort Group Period : egen mcost = mean(Cost) if Cost > 0 
    bysort Group Period (mcost) : replace mcost = mcost[1]

    Comment


    • #3
      Yep, that works perfectly. Thanks a lot, Nick.

      Comment

      Working...
      X