Announcement

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

  • Changing yes/no observations into 1/0

    I have a list of variables that contain answers Yes and No, I am trying to replace them with 1 and 0 and make all of them numeric
    The command that I use is the following:

    foreach var in MY LIST OF VARIABLES {
    replace `var' = 0 if `var'==`No'
    replace `var' = 1 if `var'==`Yes'
    destring `var', replace
    }


    Stata responds "no variables defined". I would appreciate your help on this.
    Thank you in advance!

  • #2
    Maybe try
    Code:
    foreach var of varlist <MY LIST OF VARIABLES> {
        replace `var' = strtrim(strproper(`var'))
        replace `var' = "0" if `var' == "No"
        replace `var' = "1" if `var' == "Yes"
        replace `var' = ".m" if !inlist(`var', "No", "Yes")
    }
    destring <MY LIST OF VARIABLES>, replace

    Comment


    • #3
      Dear Joseph Coveney , thank you very much for your reply.
      My observations after the commands you wrote above turned ".m". And I tried the same commands but without the line "replace `var' = ".m" if !inlist(`var', "No", "Yes")", and it did work - I got observations with 0s and 1s. Can you please explain what's the meaning of that line and what if I escaped it. Thank you in advance!

      Comment


      • #4
        Yeah, sorry, that ought to have been first, before converting Noes and Yeses to zeros and ones.
        Code:
        foreach var of varlist <MY LIST OF VARIABLES> {
            replace `var' = strtrim(strproper(`var'))
            replace `var' = ".m" if !inlist(`var', "No", "Yes") // or: assert inlist(`var', "No", "Yes")
            replace `var' = "0" if `var' == "No"
            replace `var' = "1" if `var' == "Yes"
        }
        destring <MY LIST OF VARIABLES>, replace

        Comment

        Working...
        X