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

st: check if string or numeric

From   Jacob Wegelin <[email protected]>
To   [email protected]
Subject   st: check if string or numeric
Date   Mon, 6 Oct 2008 16:44:22 -0400 (EDT)

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"


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


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


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
* For searches and help try:

© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index