Announcement

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

  • Generating variables and lables

    Hi

    I am creating a do file and have to rename and generate (gen) variables.

    is there a way that I can write a variable label at the end of the gen command? like
    gen secondary=1 if v106>=2 & v106~=. /*Mother any secondary*/

    Thanks

  • #2
    how I can create variable labels side by side with the gen command, please

    Comment


    • #3
      No, I'm afraid that is now how Stata syntax works. However, you can define a value label beforehand and attach it to a variable when you generate it. E.g.

      Code:
      label define MOM_EDU 1 "Mother any secondary" 2 "Mother primary" 3 "Mother illiterate"
      gen secondary: MOM_EDU = 1 if v106>=2 & v106~=.
      replace secondary = 2 if ...
      replace secondary = 3 if ...
      where the ... is for you to fill in.

      See also
      Code:
      help generate
      help label
      Last edited by Hemanshu Kumar; 07 Nov 2022, 17:59.

      Comment


      • #4
        I think the question is about variable labels, but the answer there is similar. There isn't official syntax for defining the variable label along with generate.

        In a first draft of a do-file you could always write some initial abbreviation and then do a replace in a text editor with repeated text such as label var

        I do have a suggestion to cut down your typing. The sample code starts

        Code:
        gen secondary=1 if v106>=2 & v106~=.
        which looks like the first part of defining an indicator (dummy) variable. (So, my guess is different from Hemanshu Kumar.)

        So I imagine a follow-up command such as

        r
        Code:
        replace secondary = 0 if secondary == .

        If that is what you want, you can get straight there with

        Code:
        gen secondary=v106>=2 & v106~=.
        if you want a (0, 1) variable or with

        Code:
        gen secondary=v106>=2 if v106~=.
        if you want a (0, 1, .) variable.

        See https://www.stata.com/support/faqs/d...rue-and-false/ or https://www.stata-journal.com/articl...article=dm0099 for more discussion.

        Comment


        • #5
          It could be programmed (and has been; see, e.g., regen from SSC) but it is probably not worth the effort. It is actually pretty hard to come up with something much shorter, more convenient, and still easily readable than

          Code:
          generate newvar =exp
          label variable newvar "label"

          Comment

          Working...
          X