Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Macros for 2 graphs. Invalid name error

    Hello,

    I have to draw I have to draw a variety of similar graphs and decided to use macros at first time. I'm working at Stata 13
    Without macros it looks like
    graph twoway (lpoly Factor1 Year if (Status == 1)&(Group == 1), degree(4))(lpoly Factor1 Year if (Status == 0)&(Group == 1), degree(4))
    graph export F1_Factor1.png
    graph twoway (lpoly Factor2 Year if (Status == 1)&(Group == 1), degree(4))(lpoly Factor2Year if (Status == 0)&(Group == 1), degree(4))
    graph export F1_Factor2.png
    ...
    and so on (it works properly)

    However, when I type
    foreach var of varlist Factor1 Factor2 {
    graph twoway (lpoly 'var' Year if (Status == 1)&(Group == 1), degree(4))(lpoly 'var' Year if (Status == 0)&(Group == 1), degree(4)), name(`var', replace)
    }

    I get an error that
    ‘var’ invalid name

    Moreover, If I type just
    foreach var of varlist Factor1 Factor2 {
    twoway scatter `var' YEAR || lfit `var' YEAR, name(gr`var', replace)
    }

    It works well, but with this syntax I can' add degree(4), which is crucial.

    Could anybody please help?

  • #2
    Hi Maria,

    Looks like you used ' instead of ` for quoting local macros. Checked it with a dummy data and works fine.

    Code:
    clear all
    
    set obs 1000
    
    *Generating the Factor variables
    loc i = 1
    while `i' < 3 {
     set seed 12345
     gen Factor`i' = rnormal()
    
     loc i = `i' + 1
    }
    
    *Generating the Group variable
    gen Year  = _n
    gen Group = 0
    replace Group = 1 if Year > 500
    
    *Generating the Status variable
    gen rndm = runiform(1,1000)
    gen Status = 0
    replace Status = 1 if rndm > 500
    
    foreach var of varlist Factor1 Factor2 {
    graph twoway (lpoly `var' Year if (Status == 1)&(Group == 1), degree(4))(lpoly `var' Year if (Status == 0)&(Group == 1), degree(4)), name(`var', replace)
    }
    
    
    foreach var of varlist Factor1 Factor2 {
    twoway scatter `var' Year || lfit `var' Year, name(gr`var', replace)
    }
    Best,
    Y

    Comment

    Working...
    X