Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: macro for the type of a variable (string/numeric)


From   Jacob Wegelin <jwegelin@vcu.edu>
To   statalist@hsphsun2.harvard.edu
Subject   st: macro for the type of a variable (string/numeric)
Date   Mon, 21 Apr 2008 11:01:12 -0400 (EDT)

The following program is a kluge to determine the type of a variable and to assign a string to a local macro which tells us the type. Is there some better way? For instance, "return list" after "describe myvar" or "codebook myvar" does not tell us this.

program returnType
args THISVAR
* Determine whether it is a numeric or string variable.
* kluge: if THISVAR is numeric with all missing, this program thinks it's string.
quietly: summarize `THISVAR'
if r(N)==0 {
local thisTYPE="string"
}
else {
local thisTYPE="numeric"
}
display "`thisTYPE'"
end

Example where one might want to obtain the type:

I'm writing code that will go through all the variables in the dataset, or through some varlist, check what kind it is, and then take different kinds of actions (e.g., tabulate vs ranksum) depending on the type of the variable and other attributes.

One concrete example: You'd like to create a new variable, "dummy", which is

- missing for cases where the variable is missing

- equal to one (1) for cases where the variable equals some specific value

- zero otherwise.

But to check for cases where the variable is missing, first we need to know whether it's string or numeric, because for a string, the check is

replace dummy=. if myvar==""

whereas if it's numeric, the check is

replace dummy=. if myvar== .

Thus a related question: Is there a command that checks for missing values regardless of the type of a variable?

Thanks for any insight

Jake

Jacob A. Wegelin
jwegelin@vcu.edu Assistant Professor
Department of Biostatistics
Virginia Commonwealth University
730 East Broad Street Room 3006
P. O. Box 980032
Richmond VA 23298-0032
U.S.A. http://www.people.vcu.edu/~jwegelin
*
* 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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index