Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, is already up and running.

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

st: RE: Re: forvalues, panel data

From   Nick Cox <>
To   "''" <>
Subject   st: RE: Re: forvalues, panel data
Date   Fri, 1 Oct 2010 11:14:42 +0100

I certainly agree with Kit that a -merge- with a file with coefficients is another way to do it, and one worth knowing about. But I can't see it's less error-prone. Either way, someone has to type the numbers in or read them from somewhere else and there is equal scope for error so far as I can see. 


Christopher Baum

Nick Cox 

> Your -forvalues- scaffolding is completely redundant, and in fact causes the same changes to be executed 11 times. But your problem does call for a loop over a varlist.
> foreach v of var <whatever> {
>        gen d`v' = .
>        replace d`v' = `v' if fyear == 1980
>        replace d`v' = `v' * 0.967059 if fyear == 1981
>        <etc>
> }
Biljana Dlab
> I have panel data (companies, fiscal years) and need to deflate numbers
> to US$ 1980
> tsset  gvkey_n  fyear
> I used forvalues function and did it like this:
> First I created variable just with dots:
> gen dI2=.
> Then simple forvalues loop
> .forvalues fyear = 1980/1990 {
> .replace dI2=I2*1 if fyear==1980
> .replace dI2=I2*0.967059 if fyear==1981
> .replace dI2=I2*0.421106 if fyear==1982
> ...
> .replace dI2=I2*0.307175 if fyear==1990
> }
> So that works, but since I have 10 variables (from I1 to I10) that need
> to be deflated, repeating the whole procedure is time consuming... so I
> tried by using var i=I1-I10, etc... but always got reply invalid
> syntax...

Rather than having an error-prone replace statement for each year (with all of those if conditions), better to merge the additional characteristics onto each observation, as described in the FAQ

For example, using the Grunfeld panel data, let's say we have a price deflator for each year and want to apply it to each of 10 investment series:

clear all
// fake deflator data in a separate file
set obs 20
g year = 1934 + _n
g defl = exp(_n/100)
save defl, replace

// apply to panel data
webuse grunfeld, clear
// make up some numbered vars
forv i=1/10 {
	g invest`i' = invest + runiform()
su invest?
// bring in the deflator
merge n:1 year using defl
// deflate each of the numbered variables in place
forv i=1/10 {
	qui replace invest`i' = invest`i' / defl
su defl invest?

*   For searches and help try:

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