I am following instructions from this link on how to append Stata files via a foreach
loop. I think that it's pretty straightforward.
However, when I try to refer to each f
in datafiles
in my foreach
loop, I receive the error:
invalid `
I've set my working directory and the data is in a subfolder called csvfiles
. I am trying to call each file f
in the csvfiles
subfolder using my local macro datafiles
and then append each file to an aggregate Stata dataset called data.dta
.
I've included the code from my do
file below:
clear
local datafiles: dir "csvfiles" files "*.csv"
foreach f of local datafiles {
preserve
insheet using “csvfiles\`f'”, clear
** add syntax here to run on each file**
save temp, replace
restore
append using temp
}
rm temp
save data.dta, replace
The backslash character has meaning to Stata: it will prevent the interpretation of any following character that has a special meaning to Stata, in particular the left single quote character
`
will not be interpreted as indicating a reference to a macro.
But all is not lost: Stata will allow you to use the forward slash character in path names on any operating system, and on Windows will take care of doing what must be done to appease Windows. Replacing your insheet command with
insheet using “csvfiles/`f'”, clear
should solve your problem.
Note that the instructions you linked to do exactly that; some of the code includes backslashes in path names, but where a macro is included, forward slashes are used instead.