Announcement

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

  • Use a for-loop to generate dummy variables

    I'm having a hard time generating dummy variables using a for loop. I have a variable with some values, now I want to create a dummy variable for each value such that if it takes the specific value it will return 1 otherwise it will return 0. I can't make it work since I always end up creating one new variable with all values being equal to 1. I have posted two pictures, the first one is the variable and the second one is how I want it to look like.
    Click image for larger version

Name:	Skærmbillede 2019-03-27 kl. 21.26.12.png
Views:	2
Size:	13.5 KB
ID:	1490497


    I want it to look like this:

    Click image for larger version

Name:	Skærmbillede 2019-03-27 kl. 21.27.28.png
Views:	1
Size:	25.4 KB
ID:	1490498
    Attached Files

  • #2
    I think you will want to read up on using the levelsof command to feed a macro extension. See https://www.stata.com/support/faqs/d...-with-foreach/

    Comment


    • #3
      If you are creating these dummy variables to be used as independent variables in a regression model, for example, you should not do so but instead take advantage of Stata's "factor variables" described in the output of help factor variables.

      Comment


      • #4
        No loop is needed. If you do really need all these, then fine, and

        Code:
        tab X, gen(X_)
        will get them in one go.

        See also dummieslab (SSC).

        Comment


        • #5
          Peter, I would try something like this:

          Code:
          levelsof x, local(xxx)
          foreach lev of local xxx {
              gen x_`lev'=0
              replace x_`lev'=1 if x==real("`lev'")
              }

          Comment

          Working...
          X