Announcement

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

  • Changing string variables to binary numeric variable

    Hi There, I'm a STATA beginner and was hoping someone could help.
    I have a variable which is a string variable with the coding yes or no
    How do I change that into a binary variable where 1=yes and 0=no ?
    for help with the example, my variable name is case_notcase
    Thank you

  • #2
    Code:
    label define case_notcase 1 "yes" 2 "no"
    encode case_not_case, gen(n_case_notcase) label(case_notcase)
    will do what you ask, creating the new numeric variable n_case_not_case. It will have a value label attached, so that in listings, etc. it will be displayed as "yes" and "no", but the actual values will be numeric as you wished for.

    But don't do it like that. Coding dichotomous variables as 1=yes and 2=no is just going to make your life difficult in Stata. If you code them as 1 = yes and 0 = no, then you will be able to use them as logical variables without awkward workaround coding.

    In the future, when asking for help with code, show example data, and please use the -dataex- command to do so. If you are running version 17, 16 or a fully updated version 15.1 or 14.2, -dataex- 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-.

    Comment


    • #3
      Thank you. This has been so helpful.

      Comment

      Working...
      X