Announcement

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

  • Using loop for generate and replace

    Hi,
    I would like to make a loop were I create 20 new variables (stretching 2001-2020) using two constrictions with if. Bellow I make an example of how I would do it manually variable by variable. How can I do this more efficient?

    gen newvariable1 = 0
    replace new variable1 = 1 if variable==1 & year2001
    gen newvariable2 = 0
    replace new variable2 = 1 if variable==1 & year2002

    gen newvariable3 = 0
    replace new variable3 = 1 if variable==1 & year2003

    gen newvariable4 = 0
    replace new variable4 = 1 if variable==1 & year2004

    gen newvariable5 = 0
    replace new variable5 = 1 if variable==1 & year2005


    /David



  • #2
    I guess that year2001 is a typo for year == 2001, and so forth.

    Code:
    forval j = 1/20 { 
        gen better_name_needed`j' = variable == 1 & year == (2000 + `j')  
    }
    and

    Code:
    tab year if variable == 1, gen(better_name_needed)
    are some of the quicker ways to do this. Here better_name_needed is a hint not to use newvar as a stub.

    See e.g. https://www.stata.com/support/faqs/d...rue-and-false/ or https://www.stata-journal.com/articl...article=dm0099 for the point that indicator variables can be generated directly in one line.

    Comment

    Working...
    X