Statalist


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

Re: st: drop variable on condition


From   SamL <[email protected]>
To   [email protected]
Subject   Re: st: drop variable on condition
Date   Mon, 21 Jul 2008 07:23:27 -0700 (PDT)

The code below is helpful, but it is also an example of why some find stata a bit more challenging than some other packages. Anytime I want to do something conditional it *seems* to take an awful lot of code, often very complicated code. Really old SPSS allowed one to just write -do if- as a "pre-command" to almost anything (and -else if's- could be added if needed), and that made the following recode or generate or "whatever" conditional. Is there any way some such easy pre-command could be instituted in stata? Is it already available, and I just have failed to find it?

Any assistance is greatly appreciated.

Sam

On Mon, 21 Jul 2008, Andrea Bennett wrote:


Ah, thank you very much!

Kind regards!

On Jul 21, 2008, at 12:54 PM, Joseph Coveney wrote:

Andrea Bennett wrote:

A quick question related to dropping variables: I would like to drop a
variable when a certain condition is met (I'm using loops to check
whether a variable is not empty for each year of observation). AFAIK, -
drop- and -keep- only refer to observations if being used
conditionally, e.g. I cannot use "drop THISVAR if mean_THISVAR<1".

So, how can I drop a variable when a certain condition is met?

--------------------------------------------------------------------------------

You can easily do both.  The do-file below illustrates dropping a variable
(for each year of observations) has any missing values.  And later it drops
it if its mean is greatern than one.

Joseph Coveney

clear *
set seed `=date("2008-07-21", "YMD")'
set obs 200
forvalues i = 1/10 {
 generate double year`i' = uniform()
 if mod(`i', 2) replace year`i' = . if uniform() > 0.99
}
replace year10 = 5 * year10
*
* Begin here
*
foreach var of varlist year* {
 capture assert !missing(`var')
 if _rc {
     display in smcl as text "variable {result}`var' " _continue
     display in smcl as text "contains missing values"
     drop `var'
     continue
 }
 summarize `var', meanonly
 if r(mean) > 1 {
     display in smcl as text "variable {result}`var'" _continue
     display in smcl as text "'s mean is greater than one"
     drop `var'
 }
}
exit


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



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