drop2
: Upgrade
If you are an avid Stata
user, who works extensively either using the command window, or dofiles, and who does lots of data-management, you are probably used to create large number of new variables, as well as delete an equally long lists of variables.
If you are like me, however, you probably get frustrated when the following happens:
You drop variables by mistake, because they start with the same name as the one you aim to delete.
A
drop
statement gives you an error, because a variable in the varlist does not exist.
Yes, both scenarios are easy to fix.
One can avoid the first problem using
set varabbrev off
.The second problem can be partially partially fixed using
capture
in front ofdrop
.
Well, today I bring you drop2
. This small program should fix the problems above, with a very simple code:
program drop2
novarabbrev {syntax anything
foreach i in `anything' {
capture noisily fvexpand `i'
if _rc == 0 {
drop `r(varlist)'
}
}
}end
It handles the first problem by forcing you to use full variable names, rather than abreviations. And it handles the second problem by going over your list of variables one by one, dropping only the ones in your dataset, giving you a warning if a variable does not exists.
To use this, you can run this code, create an ado
file with the name drop2.ado
, and save it in your personal ado folder1, or save it in the plus\d
folder. You can also download the file from here
So, just for fun, a quick example!. You can run the following code to test the command.
sysuse auto, clear
describe, simple
p pr mpg
drop2 describe, simple
drop2 pr* mpg displacementdescribe, simple
And it should produce the following ouput:
sysuse auto, clear
. data)
(1978 automobile
describe, simple
. weight turn gear_ratio
make mpg headroom length displacement foreign
price rep78 trunk
p pr mpg
. drop2 variable p not found
variable pr not found
describe, simple
. length displacement foreign
make rep78 trunk weight turn gear_ratio
price headroom
. drop2 pr* mpg displacementvariable mpg not found
describe, simple
. weight length turn gear_ratio foreign make rep78 headroom trunk
Footnotes
To see where your personal ado folder is, just type
sysdir
. ↩︎