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

st: RE: RE: Re: sorting a string variable, but not alphabetically


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: RE: Re: sorting a string variable, but not alphabetically
Date   Mon, 20 Dec 2004 20:33:42 -0000

I'm not sure what there is to chew on. 
The example shows that the program works, 
although it lacks a help file. it should 
also display an error message if no 
sorting tokens are given. 

The syntax is 

mystringsort <strvar> <token1> [<token2> [<token3 ... ]] 

so that -mystringsort- so that occurrences of 
<token1> come first, and so forth. 

Nick 
[email protected] 

TEWODAJ MOGUES
 
> Hi Joseph and Nick,
> Thanks to both of you for your ideas as to how to sort by a strin 
> variable. Joseph, your idea is a neat trick to get around the lack of 
> a transposing command that names the new variables according the 
> values of an old variable. Nick, I'm still chewing on your 
> programming 
> suggestion, I think this will be helpful beyond my specific sorting 
> problem.
> Thanks,
> Tewodaj
> 
> Message: 2         
>    Date: Wed, 15 Dec 2004 23:18:53 -0000
>    From: "Nick Cox" <[email protected]>
> Subject: st: RE: Re: sorting a string variable, but not alphabetically
> 
> But you can do this, even though Michael's main point 
> remains spot on. You just need to use a mechanism for 
> interpreting your input as labels in a particular order 
> defining a sorting variable. 
> 
> . l
> 
>      +-----------+
>      |      var1 |
>      |-----------|
>   1. | two names |
>   2. |      bird |
>   3. |       cat |
>   4. |       dog |
>   5. |     mouse |
>      +-----------+
> 
> . mystringsort var1 cat dog
> 
> . l
> 
>      +-----------+
>      |      var1 |
>      |-----------|
>   1. |       cat |
>   2. |       dog |
>   3. |      bird |
>   4. | two names |
>   5. |     mouse |
>      +-----------+
> 
> . mystringsort var1 "two names"
> 
> Here is a sketch: 
> 
> program mystringsort 
> 	version 8 
> 	gettoken varname 0 : 0 
> 	capture confirm string var `varname' 
> 	if _rc { 
> 		di as err "`varname' should be a string variable" 
> 		exit 198 
> 	} 	
> 
> 	tempvar encoded 
> 	tempname lblname
> 	local i = 1 
> 	
> 	foreach w of local 0 { 
> 		label def `lblname' `i++' `"`w'"', modify 
> 	} 
> 
> 	encode `varname', gen(`encoded') label(`lblname') 
> 	sort `encoded' 
> end 	

*
*   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