Search code examples
statastandard-deviationweightedinequality

How can I calculate the standard deviation by year using aweights?


Without using the weights is easy with egen but I don't how to use the weights.


Solution

  • Here is a silly example -- as you don't give a data example. I show two ways to do it, one with a loop over groups and the other using statsby. There are other ways using collapse (say) and yet others using community-contributed commands.

    webuse grunfeld, clear 
    
    gen sd = . 
    
    quietly forval y = 1935/1954 { 
        summarize invest [aw=mvalue] if year == `y'
        replace sd = r(sd) if year == `y'
    }
    
    save my_grunfeld 
    
    statsby SD = r(sd), by(year): su invest [aw=mvalue] 
    
    merge 1:m year using my_grunfeld 
    
    tabdisp year, c(sd  SD) format(%2.1f)
    
    ----------------------------------
         year |         sd       r(sd)
    ----------+-----------------------
         1935 |      136.2       136.2
         1936 |      175.3       175.3
         1937 |      192.4       192.4
         1938 |      116.1       116.1
         1939 |      140.0       140.0
         1940 |      196.0       196.0
         1941 |      213.8       213.8
         1942 |      197.0       197.0
         1943 |      215.4       215.4
         1944 |      237.0       237.0
         1945 |      237.3       237.3
         1946 |      283.1       283.1
         1947 |      230.8       230.8
         1948 |      224.2       224.2
         1949 |      234.7       234.7
         1950 |      274.3       274.3
         1951 |      315.5       315.5
         1952 |      377.2       377.2
         1953 |      572.6       572.6
         1954 |      664.1       664.1
    ----------------------------------