Search code examples
stata

Create a variable from Stata local


I want to know how to create a variable that stores the value of a macro. The most simple example would be something along the lines of storing the value of i' in a forvalues` loop below.

forvalues i = 1/10 {
dis `i'
}

As far as I know, I can generate variables whose name are in the format name'i' but not directly storing the value of i to another variable. What I want to do ultimately is to create a year variable that stores, obviously, the year of the dataset using a loop:

forvalues i = 2000/2020 {
use dataset`i'
gen year`i' = `i'
*gen year`i' = "`i'" ***this did not work either
}

The above code generates a bunch of

year`i' 

with 0 or NULL values.


Solution

  • The syntax looks fine to me. The error report is thus puzzling. Various comments follow:

    One guess is that although your quotation marks look fine here, you may have used different characters. The left and right single quotation marks here are in Stata terms uchar(96) and uchar(39).

    Stata does not have a concept of NULL. For a numeric variable, generic missing values are indicated by a dot, period or stop .. I can't see why you would get a variable yet also anything but one of 2000/2020 as its value. (Hence a result of 0 is also mysterious.)

    A pitfall with local macros is that code containing them must be executed as a whole; otherwise the definition of a local macro is not visible from statements in which they are referenced. But if this was biting it is hard to see why you would get any results at all.

    A common motive for doing something like this is as a step to appending datasets, one for each year. But that is made more complicated by having a different variable name in each case. The new variable should have the same name, say year, in each dataset, not different names year2000 and so on.