简体   繁体   中英

Loops with egen in Stata

I have a data set which looks as follows:

  delta    taubar
   0       1.5
  -0.223   2
   3       6.5
   0.334   2
   11      7
   2.123   1.5

delta takes different values corresponding to taubar . However, I would like to create a variable which takes the mean of delta for each value of taubar . That is, if taubar holds a value of 2 with a frequency of say 400, and for each of these 400 delta is different, I would like to create a variable which is the mean of delta for each value of taubar .

I have used

egen meandelta = mean(delta) if taubar == 2

In this case Stata creates a value of say 0.234 which is the mean of the deltas across all 400 2's. This is inefficient; also, there are 600 taubar s in the data set, each which may have 500 corresponding delta s. I would like to end up with each taubar from 1.5 to 327 corresponding to the mean of its delta s.

It's not entirely clear what you want, but there's no need to loop.

If you want to keep your original data, try:

bysort taubar: egen meandelta = mean(delta) 

You might also consider:

collapse (mean) meandelta=delta, by(taubar)

but that will destroy your data and replace it with a dataset of means.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM