Statalist


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

Re: st: check if string or numeric


From   "Eva Poen" <eva.poen@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: check if string or numeric
Date   Mon, 6 Oct 2008 21:49:12 +0100

Jacob,

see -help confirm-. The help file has an example which does just what you want.

HTH,
Eva

2008/10/6 Jacob Wegelin <jwegelin@vcu.edu>:
> 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
> 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/help.cgi?search
> *   http://www.stata.com/support/statalist/faq
> *   http://www.ats.ucla.edu/stat/stata/
>
*
*   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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index