Search code examples
statabackslashstata-macros

Save dta file with local and global variables in file name


In Stata, I try to save a dta file using local and global macros together in file names.

However, the local macros are not parsed correctly.

The global macro result is a folder directory which is:

global result "C:\Users\...\....\..."

The local macro x is defined in a loop:

foreach x of varlist ret_yyy { 
    .......
    save "$result\Reg_Coefficients\`x'", replace
}

This only produces a file under a "result" folder with name "Reg_Coefficients`x'".

What I expect is to save a file under folder "Reg_Coefficients".


Solution

  • Use forward slashes (/) instead:

    sysuse auto, clear
    global result "C:/Users/.../..../..."
    
    foreach x of varlist * { 
        display "$result/Reg_Coefficients/`x'"
    }
    
    C:/Users/.../..../.../Reg_Coefficients/make
    C:/Users/.../..../.../Reg_Coefficients/price
    C:/Users/.../..../.../Reg_Coefficients/mpg
    C:/Users/.../..../.../Reg_Coefficients/rep78
    C:/Users/.../..../.../Reg_Coefficients/headroom
    C:/Users/.../..../.../Reg_Coefficients/trunk
    C:/Users/.../..../.../Reg_Coefficients/weight
    C:/Users/.../..../.../Reg_Coefficients/length
    C:/Users/.../..../.../Reg_Coefficients/turn
    C:/Users/.../..../.../Reg_Coefficients/displacement
    C:/Users/.../..../.../Reg_Coefficients/gear_ratio
    C:/Users/.../..../.../Reg_Coefficients/foreign