Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Appropriate use of -forvalues- and -foreach- commands


From   n j cox <[email protected]>
To   [email protected]
Subject   Re: st: Appropriate use of -forvalues- and -foreach- commands
Date   Tue, 24 Apr 2007 21:13:32 +0100

gen sum = 0
gen count = 0
forval i = 1/5 {
	replace sum = sum + x`i' if bld`i' == bld & x`i' < .
	replace count = count + 1 if bld`i' == bld & x`i' < .
}
gen xmean = sum/count

Nick
[email protected]

Carter Rees

I have the variables id (person id), bld (person's building code), bld1-bld5
(building codes for 5 nominated co-workers).  I also have various co-worker
characteristics in my file.  For illustration, let x1-x5 be one of the
characteristics listed for each co-worker.  The data are constructed as:

id	bld	bld1	bld2	bld3	bld4	bld5	x1	x2	x3
x4	x5
1	10	11	10	10	10	11	6	7	2
4	2
2	11	11	11	13	13	11	6	8	4
7	0
3	12	12	12	12	12	12	6	1	2
4	3
4	13	13	10	10	10	14	10	5	10
9	5
5	14	15	14				3	10	5
1	3
6	15	15					2	6	5
2	7

For each person id, I would like to construct a variable that is the mean
value of only those co-workers who are in the same building.  For example,
the first case would only include co-workers in building 10 which would
result in an average of (7+2+4)/3 = 4.33.  -forvalues- and/or -foreach-
seems appropriate here but I can't seem to get it quite right.

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



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