Announcement

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

  • How to drop all variables whose only value is zero

    I have a dataset with hundreds of variables where many variables' only value is 0. I'd like to drop these variables without having to manually find each such variable.

    Consider the following example:
    Code:
    sysuse auto, clear
    gen problem_var1 = 0
    gen problem_var2 = 0
    I want to drop all the variables in this dataset whose only value is 0, without having to manually specify "drop problem_var1 problem_var2".

    How would I do this?

  • #2
    Thanks for the clear example. Use findname from the Stata Journal to find the variables; and then drop them.

    Code:
    . sysuse auto, clear
    (1978 automobile data)
    
    . gen problem_var1 = 0
    
    . gen problem_var2 = 0
    
    . 
    . findname, all(@==0)
    problem_var1  problem_var2
    
    . 
    . drop `r(varlist)'
    
    . 
    . ds 
    make          mpg           headroom      weight        turn          gear_ratio
    price         rep78         trunk         length        displacement  foreign
    
    . 
    
    . search findname, sj
    
    Search of official help files, FAQs, Examples, and Stata Journals
    
    SJ-20-2 dm0048_4  . . . . . . . . . . . . . . . . Software update for findname
            (help findname if installed)  . . . . . . . . . . . . . . .  N. J. Cox
            Q2/20   SJ 20(2):504
            new options include columns()
    
    SJ-15-2 dm0048_3  . . . . . . . . . . . . . . . . Software update for findname
            (help findname if installed)  . . . . . . . . . . . . . . .  N. J. Cox
            Q2/15   SJ 15(2):605--606
            updated to be able to find strL variables
    
    SJ-12-1 dm0048_2  . . . . . . . . . . . . . . . . Software update for findname
            (help findname if installed)  . . . . . . . . . . . . . . .  N. J. Cox
            Q1/12   SJ 12(1):167
            correction for handling embedded double quote characters
    
    SJ-10-4 dm0048_1  . . . . . . . . . . . . . . . . Software update for findname
            (help findname if installed)  . . . . . . . . . . . . . . .  N. J. Cox
            Q4/10   SJ 10(4):691
            update for not option
    
    SJ-10-2 dm0048  . . . . . . . . . . . . . .  Speaking Stata: Finding variables
            (help findname if installed)  . . . . . . . . . . . . . . .  N. J. Cox
            Q2/10   SJ 10(2):281--296
            produces a list of variable names showing which variables
            have specific properties, such as being of string type, or
            having value labels attached, or having a date format

    Comment


    • #3
      It's fairly straightforward even with inbuilt Stata commands:

      Code:
      foreach v of varlist * {
          capture assert `v' == 0
          if _rc == 0 drop `v'
      }

      Comment

      Working...
      X