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

Re: st: Looping questions

From   "Svend Juul" <SJ@SOCI.AU.DK>
To   <>
Subject   Re: st: Looping questions
Date   Tue, 9 Aug 2005 14:52:30 +0200

Kelly has three questions. Question 1 and 3 don't need any looping at

(1) Suppose I have a variable, say Var1
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?

sysuse "uslifeexp.dta" , clear
// sort by date , descending
gsort -year
gen x10 = (le - le[_n+10])/le[_n+10]
// or, simpler:
drop x10
gen x10 = le/le[_n+10] - 1 

(2) Now suppose I want to do this same calculation across say, a hundred
variables Var1-Var100. How can I loop across the variables in an
efficiant manner?

// now for the variables le - le_bfemale. This requires looping:
drop x10
foreach V of varlist le-le_bfemale {
  gen c`V' = `V'/`V'[_n+10]-1

(3) A more general type of loop: suppose I have 100 variables, and I
want to display the mean and std. Deviation of each varible.

// no looping needed at all:
summarize le-cle_bfemale

Hope this helps,



Svend Juul
Institut for Folkesundhed, Afdeling for Epidemiologi
(Institute of Public Health, Department of Epidemiology)
Vennelyst Boulevard 6
DK-8000  Aarhus C, Denmark
Phone: +45 8942 6090
Home:  +45 8693 7796

*   For searches and help try:

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