Announcement

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

  • egen total and weight

    Dear Stata users,

    I want to generate a new variable which equals row sum of the variables in varlist, and to each variable I must assign a weight. Now I use the following code:
    Code:
    generate newvar = var1*wgt1 + var2*wgt2 + var3*wgt3 + …
    If there's a missing value in any variable, the new variable will be set to missing also. The egen rowtotal function has an advantage that if there is any missing values it will then treat missing values as 0. However, the egen rowtotal function doesn't allow us to assign weight to each variable in varlist. Is there any command to combine the rowtotal caculation and weight assighment? Thank you very much.
    Last edited by Chen Samulsion; 03 Dec 2024, 02:34. Reason: typo

  • #2
    I would just write a customized loop, which is no more than what the essence of the code would be if this were supported by egen. It does no harm to count problems along the way.

    Code:
    gen double wanted = 0 
    gen bad_count = 0 
    
    forval j = 1/7 { 
         replace wanted = wanted + var`j' * wgt`j' if !missing(var`j', wgt`j') 
         replace bad_count = bad_count + missing(var`j', wgt`j')
    }
    where you need to substitute your own "value of 7".

    If your variable names are really messy, you will need more trickery, but tell us about that.

    There is a question of whether the weighted sum should be missing if all the components are missing.

    Comment


    • #3
      Thank you very much Nick Cox. By the way, I have never noticed that the missing function allows more than one variable missing(x1,x2,...,xn).

      Comment

      Working...
      X