Announcement

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

  • Generate new variable with multiple values

    Hello all. I'm having issues on generating a new variable with multiple values. I'm using Stata 15.1 for Windows.

    I have a variable, state, which has observations for eight US states. Initially they were string variables, so I converted them to new variables. It gave each state a value from 1 to 8.

    I would like to generate a variable, charteryear, equal to a year when the state is 3 (Florida, for example). I ran it and it stopped after the first line.

    I'd like charteryear to have a value for all 8 states. Below is what I ran:

    g charteryear = 18 if state == 1
    g charteryear = 14 if state == 2
    g charteryear = 20 if state == 3
    g charteryear = 18 if state == 4
    g charteryear = 18 if state == 5
    g charteryear = 13 if state == 6
    g charteryear = 17 if state == 7
    g charteryear = 21 if state == 8

    Also, can I run this with my state as a string variable? It is easier to remember 3 = Florida for example.

    Thank you.

  • #2
    Please take a moment to read the FAQ, especially section 12 https://www.statalist.org/forums/help. "it stopped" is not helpful.

    The command generate creates a new variable. Since it already exists after your first generate command, you cannot create it again. Instead, you want to use replace. See help replace.

    You can refer to a string variable in your if statement. But if your variable state is numeric, you cannot directly refer to its label. If you have another variable original_state_var that is a string, then you would do the following:
    Code:
    replace charteryear=20 if original_state_var=="Florida"
    Be warned that Stata matches on strings require exact matches on capitalization and spaces: "Florida " != "Florida" != "florida"
    Last edited by Carole J. Wilson; 18 Aug 2018, 10:58.
    Stata/MP 14.1 (64-bit x86-64)
    Revision 19 May 2016
    Win 8.1

    Comment


    • #3
      Thank you Carole, that worked.

      Comment

      Working...
      X