Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Looping a poisson regression analysis for levelsof a variable

From   daniel klein <>
Subject   Re: st: Looping a poisson regression analysis for levelsof a variable
Date   Fri, 12 Oct 2012 13:31:06 +0200


I did not fully understand what you are trying to do, but I hope my
comments are helpful anyway.

I guess your code fails to -restore-, because the -restore- command is
in the worng place -- outside the loop/s (so is -preserve-). From what
I understand, you want to -preserve- and -restore- the dataset
repeatedly. To do this, the commands must be used inside the loop.
However, using -preserve- and -restore- (repeatedly) is usually a very
bad idea, because it is very slow. If you really need your variables
to be coded 0 and 1, it might be faster to -generate- new variables
satisfying this condition.

Would something like this work for you?

// get levels of period and age
foreach x in period age {
	qui levelsof `x' ,l(`x')

// create dummy variables for each level of period
foreach p of loc period {
	g byte p_`p' = (periode == `p') ///
	if inlist(period, 0, `p') & !mi(period)

// now run regerssions for each level of age
foreach a of loc age {
	foreach p of loc period {
		cap noi : poisson st p_`p' if (age == `a') ,e(pyears) irr

// drop the created variables
// (alternatively you might want to create temporary variables
// in the first place)
drop p_? // given there are no other p_? variables in the dataset


Dear all,

I am running a Poisson regression on counts of surgery between two
periods (Stata 11.2), however what I have is more than two periods in
my data. Want I want to do is work out a loop that keeps the base
period, but then cycles through the other periods. In this I have
realized that my variable needs to be coded 0,1 or 1,2 etc, but my
periods are 0,1,2,3,4. I cant 'keep' periods 0 and 2 as this returns
incorrect IRRs.


levelsof period, local(levels)
levelsof age, local(age)
foreach l of local levels {
foreach a of local age {
keep if period==0 | period==`l'
tab period
replace period = 1 if period==`l'
cap nois: poisson st period if age==`a' & inlist(period, 0,`l'),
exposure(pyears) irr
*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index