help for ifwins                                               manual:  [R] none
                                                             dialog:   none    

subset dataset by if exp before subsetting by in range

ifwins [if] [in] : stata_cmd


ifwins is a prefix command that runs most any Stata command that does not modify the dataset in memory (e.g. generate, replace, etc.). ifwins will have if subset the dataset before in subsets the dataset. This is the opposite of what happens when both if and in are used in the same Stata command. For example, the following code will first subset the dataset to the first 10 observations and then subset the dataset to the specified condition:

. sysuse auto . list if foreign == 1 in 1/10

Since the auto.dta dataset is sorted by the variable foreign, the above code will not list any observations because in the first 10 observations foreign == 0 . So, if looses and in wins when "battling" over which one subsets the dataset before the other one does.

If you want to run a Stata command on a certain number of observations when a certain condition exists, you would have to:

. preserve . keep if foreign == 1 . list in 1/10 make turn weight . restore

or use ifwins as a prefix to the desired Stata command:

. ifwins if foreign == 1 in 1/10 : list make turn weight

The above will list up to the first 10 observations of when the variable foreign is equal to 1 (one). So now if wins!...but in is still helpful.


if and in are not allowed in the Stata command ifwins is specified to run. Since ifwins (when not running the list, browse, edit commands) temporarily subsets the dataset before running the submitted Stata command the observations numbers will not be the same as in the original dataset. So, the system variables _n and _N as well as the c(N) macro variable are reset to the subsetted dataset before the specified Stata command is run by ifwins. Also, ifwins will never return the error message "Obs. nos. out of range r(198)" if the range specified is at least within the number of observations in the dataset. ifwins corrects ranges specified by in to at least 1 observation of the specified condition since it is hard to know how many observations will be available after the if condition subsets the dataset.

The list, browse, edit commands are the only exceptions to the note above.


. ifwins if mpg < 25 in -10/L : list make turn weight

. ifwins if income > 1000000 in 1/200 : summarize x1 x2 x3 x4 year89 year90


Dan Blanchette The Carolina Population Center University of North Carolina - Chapel Hill, USA dan_blanchette@unc.edu

Also see

On-line: if and in