Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: RE: re: a question related to -foreach-


From   "Nick Cox" <n.j.cox@durham.ac.uk>
To   <statalist@hsphsun2.harvard.edu>
Subject   st: RE: re: a question related to -foreach-
Date   Tue, 21 Oct 2008 18:32:10 +0100

Notwithstanding this good advice, it may be of interest to see an answer
to the original question. 

First, as does Kit, I assume that the number of observations is at least
36. This can always be achieved by -set obs- if it is not correct. 

gen mean = . 
local i = 1 

qui foreach x of var b1-b36 { 
	su `x', meanonly 
	replace mean = r(mean) in `i' 
	local ++i 
}

OR

gen mean = . 
qui forval i = 1/36 { 
	su b`i', meanonly 
	replace mean = r(mean) in `i' 
} 

You will want to keep track of names too. 

For example, 

gen mean = . 
gen varname = "" 
local i = 1 

qui foreach x of var b1-b36 { 
	su `x', meanonly 
	replace mean = r(mean) in `i' 
	replace varname = "`x'" in `i' 
	local ++i 
}

Nick 
n.j.cox@durham.ac.uk 

Christopher Baum

Carlo asks
. foreach x of varlist b1-b36 {
  2. summarize `x'
3. }
  I would like to generate a newvar in which the r(mean) for each one  
of the 36 variables included in varlist are stored. How can I do this  
in Stata 9.2/SE?

No need to use a foreach loop.

tabstat b1-b36, save
mat mu = r(StatTotal)'
mat li mu

If for some reason you want these in a variable, use -svmat-:

svmat mu

which creates variable mu1, obs. 1-36.

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index