Announcement

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

  • Changing my gender variables to 1 and 2

    Hi I am new to stata and trying to change my gender variable so that 1 = female and 2 = male. How do I do this?

    What am I doing wrong?

    gen gender = 1 if whatisyourgender == "female"

    replace gender = 2 if whatisyourgender == "male"

    label define gender 1 "female" 2 "male"

    label val gender gender

    drop whatisyourethnicity

  • #2
    If whatisyourgender is a string variable that contains values "male" and "female" and nothing else, then there is nothing apparently wrong with your code. In fact it works perfectly well on my setup:

    Code:
    clear
    set obs 10
    gen whatisyourgender = cond(_n <= 5, "female", "male")
    
    gen gender = 1 if whatisyourgender == "female"
    
    replace gender = 2 if whatisyourgender == "male"
    
    label define gender 1 "female" 2 "male" 
    
    label val gender gender
    But if whatisyourgender is already a numeric variable with a value label, then you will get errors with your -gen- and -replace- commands because if a type discrepancy between it and "male" or "female".

    You don't show an example of your data, so it's hard to say. You also don't say in what way your code is not working. Are you getting incorrect results? Or error messages? Both? Is Stata crashing? Please read the Forum FAQ for excellent advice on how to pose your questions clearly. The more clearly you ask your question, the better the chance of getting a timely and helpful response.

    In the future, when you want help with code, show an example of your actual data. For showing data examples, please use the -dataex- command. If you are running version 15.1 or a fully updated version 14.2, it is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Finally, I'll just note that if whatisyour gender is, in fact, a string variable, you can accomplish this conversion more simply with a single line of code:

    Code:
    encode whatisyourgender, gen(gender)
    Read -help encode-.




    Comment

    Working...
    X