Dear Stata-Listers,
I am posting a question for the first time, so I hope I'm doing it correctly.
I have a panel data set and I want Stata to calculate the mean of a variable within a certain group. The group is identified by "country" and "period". "period" is a three-year period, i.e. there are always three year-observations in one "country period" group. I use the following code:
This works perfectly. It is only that sometimes "ideology" is missing for one or two years and with the code above Stata ignores these, i.e. mean_ideology is then calculated on the basis of the one or two non-missing observations. However, I want "mean_ideology" to be missing as soon as "ideology" is missing in one of the three years.
What happens is:
What I want is:
I thought it might make sense to first replace "ideology" with "." if there is one other missing value for ideology within a "country period" group and then calculate the mean. Based on other Stata list questions and responses I have played around with:
...?
but I have been unsuccessful.
I'd be very grateful for some help.
Thank you in advance!
Rike
I am posting a question for the first time, so I hope I'm doing it correctly.
I have a panel data set and I want Stata to calculate the mean of a variable within a certain group. The group is identified by "country" and "period". "period" is a three-year period, i.e. there are always three year-observations in one "country period" group. I use the following code:
Code:
bysort country period: egen mean_ideology = mean(ideology)
What happens is:
year | country | period | ideology | mean_ideology |
2007 | Belgium | 1 | 3 | 3 |
2008 | Belgium | 1 | 3 | 3 |
2009 | Belgium | 1 | 3 | 3 |
2010 | Belgium | 2 | 2 | 2 |
2011 | Belgium | 2 | 1 | 2 |
2012 | Belgium | 2 | 3 | 2 |
2013 | Belgium | 3 | 3 | 3 |
2014 | Belgium | 3 | . | 3 |
2015 | Belgium | 3 | . | 3 |
year | country | period | ideology | mean_ideology |
2007 | Belgium | 1 | 3 | 3 |
2008 | Belgium | 1 | 3 | 3 |
2009 | Belgium | 1 | 3 | 3 |
2010 | Belgium | 2 | 2 | 2 |
2011 | Belgium | 2 | 1 | 2 |
2012 | Belgium | 2 | 3 | 2 |
2013 | Belgium | 3 | 3 | . |
2014 | Belgium | 3 | . | . |
2015 | Belgium | 3 | . | . |
Code:
bysort country period: replace ideology = . if
but I have been unsuccessful.
I'd be very grateful for some help.
Thank you in advance!
Rike
Comment