Stata — output results of ttest

丶灬走出姿态 提交于 2019-12-12 06:12:38

问题


I have data by group_id (1,2,3 and so on). I have to run a t test by group_id. Below I am providing the code I think I will be using for each group_id. How can I modify it so that I can loop over group_ids and get an output with all the t tests combined? Will appreciate any help. Thanks.

ttest return, by(test_indicator) unequal


回答1:


The by prefix can repeat the t-test for each group_id, but it is hard to combine with other codes. Here's a quick example of using levelsof and foreach to loop through each id, run ttests, and post the results to a temporary dataset. The new dataset is then loaded and exported into an .xls file.

sysuse auto,clear
recode rep78 (1/3=1)(4/5=2),gen(id) // artificial group id
drop if missing(id) // ensure all casea have ids

tempname ttestparm
tempfile outfile

postfile `ttestparm' obs n1 n2 mu1 mu2 sd1 sd2 diff_b diff_se diff_p using `outfile',replace
levelsof id,local(idvals)
foreach i of local idvals {
    ttest mpg if id==`i', by(foreign)
    post `ttestparm' (`i') (`r(N_1)') (`r(N_2)') (`r(mu_1)') (`r(mu_2)') (`r(sd_1)') (`r(sd_2)') (`r(mu_1)'-`r(mu_2)') (`r(se)') (`r(p)')
}

postclose `ttestparm'
preserve
use `outfile',clear

export excel using "ttestout.xls", firstrow(variables) replace
restore

Note that the preserve/restore combo is only useful if there is more work to do with the original data.



来源:https://stackoverflow.com/questions/28489437/stata-output-results-of-ttest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!