I want to save the results of my Stata forvalues
loop into individual files. One component of the filename should be the value j
assigned to the macro within a forvalues
loop.
Apparently my code leads to an instruction always to save with 1995
. As such, I get messages telling me that this file already exists.
I am using the following code:
local j = 1995
forvalues `j'= 1995 / 2012 {
clear
use "/Users/carl/Desktop/STATA/Neustart/eventdates.dta", clear
keep if eventyear == `j'
sort acq_cusip eventdate
compress
save "/Users/carl/Desktop/STATA/Neustart/eventdates_`j'.dta"
}
Does anyone have an answer to that?
In your original code Stata sees `j'
inside the forvalues
command (instead of the correct j
), so it starts to evaluate that before it starts the loop. So what is eventually run is
forvalues 1995=1995/2012 {
This means that forvalues
is changing the content of the local macro confusingly but legally called `1995'
to 1995 in the first iteration, 1996 in the second iteration, etc. So when you refer to the local `j'
inside the loop, it will not have changed and remains at the original value which you defined before the loop.
The way to solve this is to replace:
local j = 1995
forvalues `j' = 1995/2012 {
with:
forvalues j = 1995/2012 {