Hoda Abou Shanab
Hoda Abou Shanab

Reputation: 1

foreach command in Stata

I am using panel data, where the variable countrynum is the country number for 138 countries and icr is the independent variable. To conduct a poolability test I have to run the below code to get the variables icr_1, icr_2, icr_3 ... icr_138.

However, the code only generates icr_1. Can someone help me understand why? I need all 138 variables.


xi, prefix(C) i.countrynum

gen Ccountrynum_1=1 if countrynum==1

replace Ccountrynum_1=0 if countrynum!=1

foreach var of varlist icr {
    foreach num of numlist 1(1)138{
        gen `var'_`num'=`var'* Ccountrynum_`num' 
    }
} 

Upvotes: 0

Views: 289

Answers (2)

Nick Cox
Nick Cox

Reputation: 37208

I don't follow this easily. Let's first note that

gen Ccountrynum_1=1 if countrynum==1
replace Ccountrynum_1=0 if countrynum!=1

simplifies to

gen Ccountrynum_1 = countrynum == 1 

That said, the double loop

foreach var of varlist icr {
    foreach num of numlist 1(1)138{
        gen `var'_`num'=`var'* Ccountrynum_`num' 
    }
} 

simplifies to a single loop

forval num = 1/138 {
    gen icr_`num' = icr * Ccountrynum_`num' 
} 

That said, it's hard to understand why that code should be expected to work as you only explain the generation of Ccountrynum_1.

It's really unusual to need that number of extra variables. In addition to @Wouter Wakker's suggestion, tabulate, generate() allows generation of indicator variables without a loop for whenever they are essential.

Upvotes: 0

Wouter
Wouter

Reputation: 3261

There are some things in your code that I would do differently, but I don't see anything that brings up an error. Rather than debugging code I think it's more useful to suggest an easier way for what you seem to be doing:

separate icr, by(countrynum)

xi is an older command which has been superseded by factor variable notation, so you only need xi in case you're using an older command that doesn't support this, which I think is not the case here.

To do a poolability test as I understand it you can run a regression with i.countrynum like this:

reg y x1 x2 x... i.countrynum
testparm i.countrynum

The output of testparm will tell you whether the country dummies are jointly significant.

Upvotes: 1

Related Questions