Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

RE: st: re: averaging within a variable

From   "kelly johnson" <[email protected]>
To   [email protected]
Subject   RE: st: re: averaging within a variable
Date   Tue, 12 Jul 2005 22:49:00 -0400

now suppose I had to do this operation in 100 different variabes (call them var1-var100), how can i code a simple loot to do that?

i want to perform this within each variable: gen Var2=(Var1+Var1[_n-1])/2 if mod(_n,2)==0

(even _n calculations are fine...)


From: Kit Baum <[email protected]>
Reply-To: [email protected]
To: [email protected]
Subject: st: re: averaging within a variable
Date: Tue, 12 Jul 2005 22:32:13 -0400

Austin said

g Var2=(Var1+Var1[_n-1])/2 if mod(_n,2)==0

-----Original Message-----
From: kelly johnson [mailto:[email protected]]
Sent: Tuesday, July 12, 2005 9:51 PM
Quick question: suppose I have a variable like this:
N Var1
1 12
2 45
3 65
100 15
How can I create a new variable whose first observation is the average of
Var1[1] and Var1[2], second observation is the avaerage of Var1[3] and
Var1[4], etc. There will be a total of 50 observations for this new
variable. Thanks in advance!

Not quite. That creates the even-numbered obs. of Var2 as the desired values, with the odd-numbered values equal to missing. To fix that up, thanks to Bill Gould's excellent tutorial at this morning's Boston SUG meeting, you may use a cute mata trick (in Stata 9, anyway):

set obs 100
g Var1=_n
g Var2=(Var1+Var1[_n-1])/2 if mod(_n,2)==0
v = st_data(.,"Var2",0) // grab nonmissing elements of Var2
v = v\null // append 50 missings
st_store(.,2,v) // stuff it back in Var2

Kit Baum, Boston College Economics

* For searches and help try:
Express yourself instantly with MSN Messenger! Download today - it's FREE!

* For searches and help try:

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