I have a question concerning the calculation of the grouped variance or standard deviation in R (survey-packge by Thomas Lumley) and Stata (using svyset and svy prefix). I'd like to know if there ara different methods used for the calculation as the grouped variances/sds are different in Stata and R.
It seems the difference is limited to the estimation of the grouped standard deviation and variance. Because grouped means are the same in both cases and also the non grouped standard deviation/variance.
I would be thankful for every idea concerning the difference in estimation. Here is my R and Stata code.
R
#libraries
library(srvyr)
library(survey)
#load data
mtcars <- read.table("https://forge.scilab.org/index.php/p/rdataset/source/file/master/csv/datasets/mtcars.csv",
sep=".",
header=TRUE)
mtcars_cplx <- mtcars %>% as_survey_design(id = cyl, weights = qsec)
# ungrouped standard deviation
var_mpg <- svyvar(~mpg, mtcars_cplx) #variance
sd_mpg<-sqrt(var_mpg) #standard deviation
sd_mpg
# grouped standard deviation
var_grouped_mpg <- svyby(~mpg, ~vs+am, mtcars_cplx, svyvar, na.rm=TRUE, na.rm.all = TRUE) #variance
sd_grouped_mpg <- sqrt(var_grouped_mpg) # standard deviation
sd_grouped_mpg
#grouped mean
mean_grouped_mpg <- svyby(~mpg, ~vs+am, mtcars_cplx, svymean, na.rm=TRUE, na.rm.all = TRUE)
mean_grouped_mpg
Stata
* load data
import delim using "https://forge.scilab.org/index.php/p/rdataset/source/file/master/csv/datasets/mtcars.csv"
svyset cyl [pweight=qsec]
* mean and standard deviation
svy: mean mpg
estat sd
* grouped mean and standard deviation
svy: mean mpg, over(vs am)
estat sd
R results
grouped mean
vs am mpg se
0.0 0 0 15.03757 1.665335e-16
1.0 1 0 20.82073 1.617214e+00
0.1 0 1 19.94862 2.190127e+00
1.1 1 1 28.42264 1.776357e-15
grouped sd
vs am mpg se
0.0 0 0 2.799371 1.053671e-08
1.0 1 0 2.471672 6.100837e-01
0.1 0 1 3.988702 3.429033e+00
1.1 1 1 4.788752 5.161914e-08
Stata results
grouped mean and sd
-------------------------------------
Over | Mean Std. Dev.
-------------+-----------------------
mpg |
_subpop_1 | 15.03757 2.778608
_subpop_2 | 20.82073 2.198151
_subpop_3 | 19.94862 3.932388
_subpop_4 | 28.42264 4.400745
-------------------------------------
Thank your for your help Stephan