Statalist


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

Re: st: check if string or numeric


From   Richard Goldstein <[email protected]>
To   [email protected]
Subject   Re: st: check if string or numeric
Date   Mon, 06 Oct 2008 16:49:58 -0400

check the help file for -ds-

Rich

Jacob Wegelin wrote:
I would like to check for type of variable (string, numeric, etc) in a program, and then take action on the basis of the type. For instance, if it's string, I encode it; else I leave it as is.

The following klugey program seems to solve the problem *part of the time*. But certainly there is a more elegant way?

capture program drop checkIfString
program define checkIfString, rclass
di "check if `1' is string or numeric"
quietly tabulate `1'
local NobsRegardlessOfStringOrNumeric=r(N)
quietly summarize `1'
local NobsOnlyIfNumeric=r(N)
di "NobsRegardlessOfStringOrNumeric: `NobsRegardlessOfStringOrNumeric' and NobsOnlyIfNumeric: `NobsOnlyIfNumeric'"

if (`NobsRegardlessOfStringOrNumeric'>0) & ( `NobsRegardlessOfStringOrNumeric' == `NobsOnlyIfNumeric' ) {
return local type="numeric"
}

else {

if (`NobsRegardlessOfStringOrNumeric'>0) & ( `NobsOnlyIfNumeric'==0 ) {
return local type="string"
}

else {
return local type="not sure"
}

}
end

clear
set obs 5
gen x=_n
gen y="a"
gen z=.
gen w=""

list

checkIfString x
return list
checkIfString y
return list
checkIfString z
return list
checkIfString w
return list


This seems like a FAQ but I haven't found the answer yet on the Web.

Thanks for any tips

Jake

Jacob A. Wegelin
[email protected] 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/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