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

st: RE: forvalues with dates


From   "Nick Cox" <n.j.cox@durham.ac.uk>
To   <statalist@hsphsun2.harvard.edu>
Subject   st: RE: forvalues with dates
Date   Fri, 21 Oct 2005 13:19:21 +0100

Kit's code indicates some nice technique but does 
not spell out the implications for Eric's question. Eric 
has a series of variables set up for different 
years and months. A shorter and more direct
reply to his question is that there wouldn't 
seem to be a really neat way of cycling across
his variables with -forvalues-: for that he
needs a different data structure or a different 
set of variable names. 

On the other hand there are awkward ways of 
doing it that should work. 

Assume first that his variables run from amount_1996_11
to amount_2000_4. Then 

forvalues y=1996/2000 {
	forvalues m = 1/12 {
		capture replace amount_`y'_`m' = .....
	}
}

is one way of doing it. Another is something
like 

local t1 = ym(1996,11) 
local t2 = ym(2000,4)

forval t = `t1'/`t2' { 
	local y = yofd(dofm(`t'))
	local m = month(dofm(`t'))
	replace amount_`y'_`m' = ...
} 

although note that I've not tested this
and that there may be a cleaner solution. 
But the solution above could be rewritten 
on three lines, one just a brace, but at
the cost of some unreadability. 

Nick 
n.j.cox@durham.ac.uk 

Kit Baum

> . webuse wpi1,clear
> 
> . su t if tin(1979q3,1987q1)
> 
>      Variable |       Obs        Mean    Std. Dev.       Min  
>       Max
> -------------+--------------------------------------------------------
>             t |        31          93    9.092121         78  
>       108
> 
> . local lo=r(min)
> 
> . local hi=r(max)
> 
> . forv i=`lo'/`hi' {
>    2. local yy=year(dofq(`i'))
>    3. local qq=quarter(dofq(`i'))
>    4. di "`i'  `yy'  `qq'"
>    5. }
> 78  1979  3
> 79  1979  4
> 80  1980  1
<snip> 
> 106  1986  3
> 107  1986  4
> 108  1987  1

Eric Wruck 

> > I have found forvalues to be a huge help & have done things like
> >
> >    forvalues y=1997(1)1999 {
> >      forvalues m = 1(1)12 {
> >        replace amount_`y'_`m' = .....
> >      }
> >    }
> >
> >
> > But my problem is that I actually have to process the last couple
> > months of 1996 and the first few months of 2000 as well.  So it
> > didn't seem like I could handle this within the forvalues block &
> > therefore have to treat those months separately outside these loops.
> > Is there a way to go through say November 1996 through April 2000
> > with two forvalues loops?

*
*   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/



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