Solution

Consider grade twelve of school one and grade one of school two. If you specify by school: Stata understands that the first is the end of a school's data and the second is the beginning of a different school's data. But without by school: Stata sees them as adjacent observations. Thus the command:

gen peerGroup=students+students[_n+1]+students[_n-1]

would count the first graders in school two among the peers of the twelfth graders in school one.

This code is written on the assumption that adjacent observations represent "adjacent" grades. If some schools do not have some observations for some grades, that assumption is violated. For example, if a school did not have an observation for grade three, students[_n+1] for the second graders would be the fourth graders, and thus the fourth graders would be considered peers of the second graders.

Last Revised: 1/26/2010