Statalist


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

Re: st: check if string or numeric


From   Caleb Southworth <[email protected]>
To   [email protected]
Subject   Re: st: check if string or numeric
Date   Mon, 6 Oct 2008 13:51:43 -0700 (PDT)

ds , has(type string)

On Mon, 6 Oct 2008, 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/
:

Caleb Southworth
Associate Professor
University of Oregon Sociology
*
*   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