Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Drop variables satisfying a condition


From   "David Elliott" <dcelliott@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Drop variables satisfying a condition
Date   Fri, 6 Jul 2007 12:55:27 -0300

// Remove empty variables from dataset
foreach var of varlist * { // this does all vars or you could restrict
it to certain variables
   capture confirm string `var'  // need to handle string and number
differently
   if !_rc==0 { // i.e. is not string
       quietly summarize `var'
       if `r(sum)' == 0  { // r(sum) is returned by summarize
            drop `var'
            display as txt "Dropping " as result "`var'"
           }
       }
       else { // if a string
           quietly count if `var' == ""
           if `r(N)' == `c(N)' { // r(N) is returned by count
               drop `var'
               display as txt "Dropping " as result "`var'"
               }
           }
   }

There are a couple of useful programming points in the above:
* foreach ... of varlist ... to loop through variables
* capture confirm string to test a variable's datatype
* using the return variables left by other commands

David Elliott MD, MSc
*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index