Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: sort


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: sort
Date   Tue, 28 Jun 2005 22:31:02 +0100

If you -sort- on any variable, only the order 
of the observations changes, not their values. 

Alternatively, what you want may be what 
I call a -cosort-. -save- your data first 
just in case this is not what you want. 

*! 1.0.0 NJC 3 November 1999 
program define cosort
	version 6 
	syntax varlist(min=2) [if] [in] 
	tokenize `varlist' 
	tempvar touse order 
	mark `touse' `if' `in' 
	qui replace `touse' = 1 - `touse' 
	sort `touse' `1' 
	gen long `order' = _n
	mac shift 
	qui while "`1'" != "" { 
		tempvar copy 
		local type : type `1' 
		gen `type' `copy' = `1' 
		sort `touse' `1' 
		replace `1' = `copy'[`order']
		drop `copy' 
		mac shift 
	}	
	sort `order' 
end

.-
help for ^cosort^
.-

Sort variables and align in sorted order 
----------------------------------------

    ^cosort^ varlist [if] [in] 

Description
-----------

^cosort^ sorts each variable in varlist and replaces variables so that all 
are in sorted order, aligned so that the first of each is in the first 
observation, the second of each is in the second observation, and so on. 
Variables may be numeric or string. 

Observations selected by ^if^ and/or ^in^ are placed first in the data set. 

Suppose we have 

      ^a   b   c^ 
      3   7   13 
      1   8   12
      2   9   11 

After ^cosort a b c^ we have 

      ^a   b   c^
      1   7   11
      2   8   12
      3   9   13 


Warning
-------

^cosort^ is a rarely needed command. Almost all sorting problems call for 
@sort@ or @gsort@.

Example where it may be appropriate: sorting independent batches of random 
numbers held in separate variables. 

^cosort^ destroys information in your data set in so far as values in each 
observation are typically not kept together. To be on the safe side, ^save^ 
your data before issuing ^cosort^. 
 

Examples
--------

    . ^cosort x y^


Author
------

         Nicholas J. Cox, University of Durham, U.K.
         n.j.cox@@durham.ac.uk


Also see
--------

On-line: help for @sort@, @gsort@

Nick 
[email protected] 

NEYMOTIN, FLORENCE
 
> is there a way to sort just ONE variable without changing the 
> rest of the dataset? i.e. I want to 
> sort EACH variable seperately and leave the rest of the 
> dataset the same...

*
*   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–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index