Announcement

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

  • egen by(id) returning zero for missing values

    Dear Statalists, please, could anyone help me?
    I have the data set example below and am trying to use egen to calculate by group, but the results for obs with missing values are returning 0. How can I fix this?
    Many thanks.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(id x1 x2 num den totalnum totalden total)
    1  .  3         .  .3333333         0  .4242424         0
    2 17 10       1.7        .1 2.7555556 .15555556 17.714285
    3  .  .         .         .       1.2       .05        24
    1  . 11         .  .0909091         0  .4242424         0
    2 19 18 1.0555556 .05555556 2.7555556 .15555556 17.714285
    3 24 20       1.2       .05       1.2       .05        24
    end

    Code:
    gen num = x1/x2
    
    gen den = 1/x2
    
    egen totalnum = total(num), by(id)
    
    egen totalden = total(den), by(id)
    gen total = totalnum/totalden

  • #2
    .
    Last edited by juliana pinto; 29 Jan 2022, 00:56.

    Comment


    • #3
      egen has a missing option:

      Code:
      bys id: egen totalnum = total(num), missing

      Comment


      • #4
        Stata's logic was that if you want to regard (say) the sum of 1, 2, 3 as 6 and the sum of 1, 2, 3, and missing as 6, and the sum of 1, 2, 3, missing and missing as 6, and so on, then the rule you are using is that the sum of missings is (is regarded as) zero. Note that Stata uses this rule in summarize in returning r(sum) and in the function sum() which also ignores missings.

        As said, if you don't want to do that, egen has a documented option to insist that the sum of one or more missings is itself reported as missing.
        Last edited by Nick Cox; 29 Jan 2022, 05:39.

        Comment


        • #5
          Thank you both very much for the solution and explanations!

          Comment

          Working...
          X