Announcement

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

  • do loop in stata

    Hi Friend,

    I have a dataset with 40 variables. I need to create a new variable which added a suffix "comment" from the exiting variables and assigned value according to two variables.


    I do not want to writ the code like this for the 40 variables. How can I write the code such as a do loop in stata?

    Code:
     gen carry_comment = "wrong"
    if (carry == 0 & carryhr ~= 0 & carryhr ~= .) | (carry == 1 & (carryhr == 0 | carryhr ==.))
    data have:
    ----------------------- copy starting from the next line -----------------------
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str18 ssid byte carry double carryhr str5 
    "15SWHB-LND-245-MVR" 1 0 
    end
    ------------------ copy up to and including the previous line ------------------


    data I want for one of the variable:

    ----------------------- copy starting from the next line -----------------------
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str18 ssid byte carry double carryhr str5 carry_comment
    "15SWHB-LND-245-MVR" 1 0 "wrong"
    end
    ------------------ copy up to and including the previous line ------------------


    Many thanks.









  • #2
    I think something did not work with your attempt to post example of data. ( I see only one row.)

    Otherwise you loop through variables in Stata by



    foreach lname of varlist varlist {


    }

    Comment


    • #3
      Joro Kolev ,Thanks. Yes. Because there is only one missing out of 250 in this variable, that is why I post only one row. I have looked for some post of foreach statement, but I just do not know how to use it. I think I need to create two loops.

      Comment


      • #4
        Assuming you have pairs of variables, one ending in hr and the other not, as in your example with carryhr and carry, the following would seem to start you in the direction you want to go.
        Code:
        * Example generated by -dataex-. To install: ssc install dataex
        clear
        input str18 ssid byte carry double carryhr str5 
        "15SWHB-LND-245-MVR" 1 0 
        end
        foreach v of varlist carry {
            gen `v'_comment = "wrong" if (`v' == 0 & `v'hr ~= 0 & `v'hr ~= .) | (`v' == 1 & (`v'hr == 0 | `v'hr ==.))
            }
        list, clean noobs abbreviate(20)
        Code:
        . list, clean noobs abbreviate(20)
        
                          ssid   carry   carryhr   carry_comment  
            15SWHB-LND-245-MVR       1         0           wrong

        Comment


        • #5
          William Lisowski Thank you so much! The code is great!

          Comment

          Working...
          X