Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

Re: st: encode


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: encode
Date   Mon, 5 Sep 2011 11:43:26 +0100

This is programmable. The code for the solution below is almost the
same as -multencode- (SSC). You'd need to write your own help by
analogy with the help for -multencode-. Note that you can "encode"
several string variables at once.

*! 1.0.0 NJC 5 Sept 2011
program zeroencode
	version 9
	syntax varlist(string) [if] [in] , Generate(str) [ label(str) FORCE ]

	marksample touse, novarlist
	qui count if `touse'
	if r(N) == 0 error 2000

	if "`label'" == "" local label : word 1 of `varlist'

	if "`force'" == "" {
		capture label list `label'
		if _rc == 0 {
			di as err "{p}value labels `label' already exist; " ///
			"specify -force()- option to overwrite{p_end}"
			exit 498
		}
	}  			

	local nvars : word count `varlist'
	local mylist "`varlist'"
	local 0 "`generate'"
	syntax newvarlist
	local generate "`varlist'"
	local ngen : word count `generate'

	if `nvars' != `ngen' {
		di as err "`nvars' " plural(`nvars', "variable") ///
		"but `ngen' new " plural(`ngen', "name")
		exit 198
	}

	mata : def_new_zero_vlbl("`mylist'", "`touse'", "`label'")

        tokenize "`generate'"
        local j = 1
	foreach v of local mylist {
		encode `v' if `touse', gen(``j'') label(`label')
		qui compress ``j''
		local ++j
	}
end

mata :

void def_new_zero_vlbl(string scalar varnames, string scalar
tousename, string scalar lblname)
{
	string matrix y
	string colvector vals
	real scalar j

	st_sview(y, ., tokens(varnames), tousename)
	vals = J(0, 1, "")
	
	for(j = 1; j <= cols(y); j++) {
		vals = vals \ uniqrows(select(y[,j], y[,j] :!= ""))
	}

	vals = uniqrows(vals)
	_sort(vals, 1)
	st_vlmodify(lblname, (0::(rows(vals) - 1)), vals)
}	

end


On Mon, Sep 5, 2011 at 11:29 AM, Artur Kyral (CMA)
<[email protected]> wrote:
> Hi,
>
>
>
> I was wondering if there is either a base or a user-defined command or an
> option similar to command encode that creates numeric variables with data
> values initiating at 0 instead of 1?
>
*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index