Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
st: Using the foreach command to solve a problem with multilevel data
From
John Marvel <[email protected]>
To
[email protected]
Subject
st: Using the foreach command to solve a problem with multilevel data
Date
Wed, 17 Mar 2010 01:58:18 -0400
I have data on individuals ("subjectid") nested in groups ("groupid").
Within groups, individuals have varying levels of authority
("authority"), ranging from a low of 1 to a high of 5. I also have
data on each individual's age ("age"). I have created a variable
called "meanage," which equals the within-group mean of age for each
authority level:
bysort groupid authority: egen meanage = mean(age)
What I want to do is create a new variable (call it "meanageup") that,
for individual i (in group g) with authority level a, is equal to
"meanage" for authority level a + 1 (in group g). In other words, if an
individual in group x has an authority level of 1, I want "meanageup"
for that individual to equal the mean age of all group x individuals
who have an authority level of 2. And if an individual in group x has
an authority level of 2, I want "meanageup" for that individual to
equal the mean age of all group x individuals who have an authority
level of 3, etc.
For an idea of what the data look like, see below.
Thus, for subjectids 1, 2, and 3, I want "meanageup" to equal 28.5;
for subjectids 4 and 5, I want "meanageup" to equal 34, etc. Because
the data set is large, I'd like to automate this as much as possible.
(It's not clear to me how I would do this with the foreach
command, and I haven't been able to track down an
answer in the statalist archives or elsewhere online).
groupid subjectid authority age meanage
1 1 1 25 26
1 2 1 25 26
1 3 1 28 26
1 4 2 28 28.5
1 5 2 29 28.5
1 6 3 34 34
1 7 3 34 34
1 8 4 40 42
1 9 4 44 42
1 10 5 50 50
2 11 1 23 23.5
2 12 1 24 23.5
2 13 2 30 31
2 14 2 31 31
2 15 2 32 31
2 16 3 36 37
2 17 3 38 37
2 18 4 44 46
2 19 4 48 46
2 20 5 50 51
2 21 5 52 51
I would greatly appreciate any suggestions.
Thank you very much,
John
*
* 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/