Announcement

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

  • Loops with generate

    Hi all,

    I am trying to generate a dummy variable identifying missings values for a long list of variables.
    So started by generating

    Code:
     ​​​​​gen misweekday=1 if missing(weekday)
    replace misweekday=0 if !mis(weekday)
    And this does work. But I was trying to do some kind of loop with it, so I wouldn't have to edit the code for 100 or so variables.


    I tried
    Code:
    global mis weekday channel time 
    
    foreach x of varlist $mis {
    gen mis=1 if missing($mis)
    }
    But it doesn't work at all.
    Does anyone have an idea on how I can make it work?
    I am using STATA 15
    Thank you!

  • #2
    Code:
    sysuse auto, clear
    
    replace foreign = . if foreign==0
    
    foreach v of varlist * {
        gen mis_`v' = missing(`v')
        }

    Comment


    • #3
      Code:
      global mis weekday channel time
      egen mis = rowmiss($mis)
      replace mis = 1 if mis!=0
      will perhaps do something useful for you - you say you want to generate "a dummy variable" which I took to mean a single variable that indicates if any variable in the list has a missing value.

      Let us suppose that those three variables appear in your dataset in that order with no variables that are not to be checked stuck into the middle. Then
      Code:
      egen mis = rowmiss(weekday-time)
      replace mis = 1 if mis!=0
      will do what you want without needing to type the names of all the variables.

      See the output of help varlist for details on variable list possibilities.
      Last edited by William Lisowski; 28 Mar 2019, 14:52.

      Comment


      • #4
        Hi Brian and William,

        thank you very much for your solutions!
        I wasn't very clear, sorry. But I wanted to generate a dummy per variable in my variable list, so Brian's code did it.
        Many thanks, this made the coding process a lot smoother!

        Comment

        Working...
        X