Economics should be open

July 29, 2009

Stata, control flow based on variable type

Filed under: Uncategorized — howardchong @ 12:45 am

Suppose you want to write a function (or a loop), where you do something to every variable that depends on its type. In matlab, I would use “isnumber”, etc, or just use the function that returns the type of the variable.

I couldn’t find such a function in stata. There is no “isnumeric” or “isfloat” function.

There is an extended function called “type”. This is my prefered way to do it:

local mytype : type myvarname
disp "`mytype'"

They also have “confirm”, which works:

http://www.stata.com/help.cgi?confirm

COPIED FROM STATA (accessed 7/28/2009):

You are writing a command that performs some action on each of the
    variables in the local macro varlist.  The action should be different for
    string and numeric variables.  The confirm command can be used here in
    combination with the capture command to switch between the different
    actions:

        foreach v of local varlist {
                capture confirm string variable `v'
                if !_rc {
                        action for string variables
                }
                else {
                        action for numeric variables
                }
        }

    An alternative solution using inline expansion of the extended macro
    function :type (see local) reads

        foreach v of local varlist {
                if substr("`:type `v''",1,3) == "str" {
                        action for string variables
                }
                else {
                        action for numeric variables
                }
        }
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: