Search code examples
statasurvey

Extract the mean from svy mean result in Stata


I am able to extract the mean into a matrix as follows:

svy: mean age, over(villageid)
matrix villagemean = e(b)'
clear
svmat village

However, I also want to merge this mean back to the villageid. My current thinking is to extract the rownames of the matrix villagemean like so:

local names : rownames villagemean

Then try to turn this macro names into variable

foreach v in names {
    gen `v' = "``v''"
}

However, the variable names is empty. What did I do wrong? Since a lot of this is copied from Stata mailing list, I particularly don't understand the meaning of local names : rownames villagemean.


Solution

  • It's not completely clear to me what you want, but I think this might be it:

    clear
    set more off
    
    *----- example data -----
    
    webuse nhanes2f
    
    svyset [pweight=finalwgt]
    svy: mean zinc, over(sex)
    
    matrix eb = e(b)
    
    *----- what you want -----
    
    levelsof sex, local(levsex)
    local wc: word count `levsex'
    
    gen avgsex = .
    forvalues i = 1/`wc' {
        replace avgsex = eb[1,`i'] if sex == `:word `i' of `levsex''
    }
    
    list sex zinc avgsex in 1/10
    

    I make use of two extended macro functions:

    local wc: word count `levsex'
    

    and

    `:word `i' of `levsex''
    

    The first one returns the number of words in a string; the second returns the nth token of a string. The help entry for extended macro functions is help extended_fcn. Better yet, read the manuals, starting with: [U] 18.3 Macros. You will see there (18.3.8) that I use an abbreviated form.

    Some notes on your original post

    Your loop doesn't do what you intend (although again, not crystal clear to me) because you are supplying a list (with one element: the text name). You can see it running and comparing:

    local names 1 2 3
    
    foreach v in names {
        display "`v'"
    }
    
    foreach v in `names' {
        display "`v'"
    }
    
    foreach v of local names {
        display "`v'"
    }
    

    You need to read the corresponding help files to set that right.

    As for the question in your original post, : rownames is another extended macro function but for matrices. See help matrix, #11.

    My impression is that for the kind of things you are trying to achieve, you need to dig deeper into the manuals. Furthermore, If you have not read the initial chapters of the Stata User's Guide, then you must do so.