Announcement

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

  • Create new variables in a loop

    Dear Statalist users,

    I am trying to generate a new variable in a loop however I get the error code
    Code:
    variable diff already defined r(110);
    This is the code I am using:
    Code:
    use http://www.stata-press.com/data/r13/auto,clear
    
    foreach var in price mpg length {
            
            gen diff = `var' - weight 
                sum diff, d
                local diffmean : display %5.3f r(mean)
                local diffsd : display %5.3f r(sd)
                local upper = r(mean) + 1.96 * r(sd)
                local lower = r(mean) - 1.96 * r(sd)
        
            gen mean1=(`var' + weight)/2 
            
        twoway (scatter diff mean1, mcolor(blue)), ///
            yline(0, lc(blue) lpattern(dash) lwidth(medium)) ///
            yline(`diffmean', lc(black) lwidth(medium)) ///
            yline(`upper', lc(black) lwidth(medium)) ///
            yline(`lower', lc(black) lwidth(medium)) ///
            legend(off) aspectratio(1) ///
            xlabel(2000(2000)10000) xscale(range(2000 10000)) ///
            ylabel(-12000(4000)12000) yscale(range(-12000 12000)) ///
            text(12000 2000 "Mean = `diffmean'", place(e)) text(10000 2000 "SD = `diffsd'", place(e)) ///
            ytitle("Difference, `var' - Weight") xtitle("Mean, `var' weight")
            
            gr_edit .plotregion1.style.editstyle boxstyle(linestyle(color(none))) editcopy
            
        }
    Is there a way to generate the new variable in increasing numbers e.g., diff1 diff2 diff3 etc., or a way to replace the variable after each loop?

    I look forward to your response.

    (ps I already know In the graphics area that I need to change the label range for each variable, I know how to use locals for that for each variable)

    Annabelle

  • #2
    You can

    Code:
    generate diff = . 
    before the loop and then replace it each time around.

    (It is certainly possible to code up diff1 diff2 etc, but I would prefer the method just mentioned.)

    As the auto data is bundled with your Stata, and everyone else's,

    Code:
    sysuse auto, clear 
    is fine for reproducible examples without downloading the dataset from Texas.

    Comment


    • #3
      Hi Nick,

      This has worked perfectly, thank you for your help.

      Comment

      Working...
      X