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: reverse lookup


From   daniel klein <klein.daniel.81@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: reverse lookup
Date   Wed, 9 Jan 2013 18:13:19 +0100

Guess at this point the Mata approach, sketched out earlier, seems
more convenient. With numeric variables only, and not "too many
values", one could also think of -tabulate- with -matrow- option.

pr vlookup ,rclass
	vers 9.2
	
	syntax varname [if][in] [, Local(name local)]
	
	marksample touse ,nov s
	qui cou if `touse'
	if !(r(N)) err 2000
	
	cap conf numeric v `varlist'
	loc isstr = _rc
	
	m : mvlookup("`varlist'", "`touse'", `isstr')
	
	di `"`macval(val)'"'
	
	if ("`local'" != "") c_local `local' `"`macval(val)'"'
	ret loc values `"`macval(val)'"'
	ret sca matches = `matches'
end

vers 9.2
m :
void mvlookup(string scalar varn, string scalar tu, real scalar isstr)
{
	transmorphic matrix X
	string scalar val
	
	if (isstr) X = st_sdata(., varn, tu)
	else X = strofreal(st_data(., varn, tu), st_varformat(varn))
	
	if (isstr) {
		if (!strpos(X[1, 1], `"""')) val = `"""' + X[1, 1] + `"""'
		else val = "`" + `"""' + X[1, 1] + `"""' + "'"
	}
	else val = X[1, 1]
	
	if (!allof(X, X[1, 1])) {
		for (i = 2; i <= rows(X); ++i) {
			if (isstr) {
				if (!strpos(X[i, 1], `"""')) {
					val = val + " " + `"""' + X[i, 1] + `"""'
				}
				else {
					val = val + " " ///
					+ "`" + `"""' + X[i, 1] + `"""' + "'"
				}
			}
			else val = val + " " + X[i, 1]
		}
	}
	st_local("val", val)
	st_local("matches", strofreal(rows(X)))
}
end

Best
Daniel
-- 
Yes, the sort works as well for strings.

I'm thinking of a program will return the list of matches, along with
a flag regarding uniqueness, because in some contexts it's good have
the set of matching values. But no need to post it here (grin).
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index