如何使用 aweights 按年计算标准偏差?

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

egen不使用权重很容易,但我不知道如何使用权重。

这是一个愚蠢的例子——因为你没有给出数据例子。我展示了两种方法,一种是在组上循环,另一种是使用 statsby。还有其他使用 collapse(比如)的方法,还有其他使用 community-contributed 命令的方法。

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
----------------------------------