[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

From |
Kit Baum <baum@bc.edu> |

To |
statalist@hsphsun2.harvard.edu |

Subject |
st: looping questions |

Date |
Tue, 9 Aug 2005 08:53:52 -0400 |

Kelly asked

> How can I write a fundction that calculates the change between successive

> observations of 10 elements of this variable? Ie. Assume the data is

> sorted by date, decending. The first observation is

> (Var1[_n] -Var1[_n+10])/Var[_n+10], the second observation is

> (Var1[_n+2]-Var1[_n+11])/Var1[_n+11], and so on...Is this an instance

> where I can use the -rolling- command? If so, how?

and R.E. replied

local i=10

while `i'<_N { //"_N" is the number of observations

replace myvar = (Var[_n]-Var[_n+`i'])/Var[_n+`i']) if _n=(`i'-9)

local i=`i'+1

}

The original formula is very strange; normally we calculate a change as the difference between now and a while ago, not the other way around. That is, to calculate a year-over-year price change from monthly data, I would do

infl_t = ( P_t - P_{t-12} ) / P_{t-12}

But presuming Kelly really wants what she says, and that these are time series data (or could be tsset as such) a more Stataish way to do that would be something like

webuse wpi1

g wpid = (wpi - F10.wpi)/F10.wpi

which will avoid the explicit "while" loop (always a good idea). In fact one would never need the explicit loop; you could do

g wpid = (wpi - wpi[_n+10] ) / wpi[_n+10]

but I would much rather use the time series operators. They don't make mistakes.

If you want to loop this calculation, just put the variable names in a local macro and use a foreach loop. Or, if they are numbered x1- x100, use a forvalues loop, e.g.

forvalues v=1/100 {

g wpi`v' = etc.

Kit Baum, Boston College Economics

http://ideas.repec.org/e/pba1.html

*

* For searches and help try:

* http://www.stata.com/support/faqs/res/findit.html

* http://www.stata.com/support/statalist/faq

* http://www.ats.ucla.edu/stat/stata/

- Prev by Date:
**st: RE: Generating random variable through rnd and rndwei and Weibull fits** - Next by Date:
**Re: st: Looping questions** - Previous by thread:
**st: Re: Looping questions** - Next by thread:
**Re: st: Looping questions** - Index(es):

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