Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Alphabetical sort by value label


From   "David Elliott" <[email protected]>
To   [email protected]
Subject   Re: st: Alphabetical sort by value label
Date   Wed, 17 Dec 2008 21:52:13 -0400

Further to earlier variations on a program to create a variable
alphabetically ordered by the value label - Once again, my thanks to
Sergiy - I had forgotten about -uselabel- which is key to the process.
 I still think this can be done in mata with potential speed
advantages, but no mata experts have risen to the bait.

I've taken Sergiy's code and modified it to accept a varlist, to
prepend a user specified prefix, and to do a check for a value label.
The code is as follows:

---------begin code - watch for wrapping------------
program define labvalsort2
version 9.0

*! version 1.0.0  2008.12.17
*! Create new variable(s) with alphabetically ordered value labels
*! by Sergiy Radyakin & David C. Elliott

syntax varlist [, pre(string)]
if "`pre'"=="" { //user-specified prefix for newvar and new val lab
	local pre _
	}
tokenize `varlist'
local nvars :word count `varlist'
forvalues i=1/`nvars' {
	local vallab : val lab ``i''
	if "`vallab'"=="" {
		di "{err:Warning: ``i'' has no value labels, skipped}"
		continue
		}
	preserve
	uselabel `vallab', clear
	sort label
	generate `pre'``i'' = _n
	// create new alpha ordered value label
	*lab def `pre'`vallab' `=`pre'``i''[1]' `"`=label[1]'"'
	forvalues j=1/`c(N)' {
		lab def `pre'`vallab' `=`pre'``i''[`j']' `"`=label[`j']'"', add
		}
	lab val `pre'``i'' `pre'`vallab'
	ren value ``i''
	tempfile reorder
	sort ``i''
	keep ``i'' `pre'``i''
	qui save `"`reorder'"'
	restore
	sort ``i''
	qui merge ``i'' using `"`reorder'"'
	drop _merge
	}
end
---------------------------end code----------------------------

One can test this with:

---------begin code - watch for wrapping------------
* testing labvalsort2
sysuse nlsw88.dta
lab list indlbl
tab ind
labvalsort2 industry, pre(_)
lab list _indlbl
tab _ind
sort _ind
---------------------------end code----------------------------

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