Announcement

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

  • Selecting values from a list in a local macro

    Hi all,

    I have 55 datasets, all with the same set of 60 variables, but some of them have missing data for some of the variables. I want to loop my code over each dataset, but select which variables to choose for each command based on which variables don't have missing data. I am trying something like this to create a local macro with variable names that don't have missing data. I have created a new local macro `data', that is 0 when the data is missing. Is there a way to remove these from the list, as well as the related variable names in `x_all'? i.e. in the example below, to create a new local macro x_all_2 with only rep78 and turn.

    Code:
    sysuse auto, clear
    gen colour = .
    
    local x_all rep78 turn colour
    local data
    foreach empty of local x_all {
                     tab `empty'
                     local data `data' `r(N)'
                     }
    di "`data'"
    Thanks,

    Sonia

  • #2
    Code:
    sysuse auto, clear
    gen colour = .
    
    local x_all rep78 turn colour
    foreach var of local x_all {
        count if missing(`var')
        if r(N) < _N {
            local x_nonempty `x_nonempty' `var'
        }
    }
    di "`x_nonempty'"
    
    // bonus:
    // once you have x_all and x_nonempty, you can easily get x_empty
    // see -help macrolists- for this trick
    local x_empty : list x_all - x_nonempty
    
    di "`x_empty'"
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Thanks Maarten! That's just what I needed!

      Comment


      • #4
        findname (Stata Journal) can tell you which variables are completely non-missing, completely missing, and so forth.

        That permits a variation on Maarten's theme.

        Code:
        . sysuse auto, clear
        (1978 Automobile Data)
        
        . gen colour = .
        (74 missing values generated)
        
        . findname, any(missing(@)) local(bad) 
        rep78   colour
        
        . findname, all(missing(@)) local(verybad) 
        colour
        
        . findname, all(!missing(@)) local(good) 
        make          mpg           trunk         length        displacement  foreign
        price         headroom      weight        turn          gear_ratio

        Comment


        • #5
          Thanks Nick! That's a neat tip too.

          Comment

          Working...
          X