Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Using the format of a variable to trigger different command


From   Maarten Buis <[email protected]>
To   [email protected]
Subject   Re: st: Using the format of a variable to trigger different command
Date   Thu, 26 Jul 2012 12:34:22 +0200

On Thu, Jul 26, 2012 at 12:04 PM, Erik Lenguerrand
<[email protected]> wrote:
> I would like to use the "foreach varlist" command to loop over a large list
> of variables  to automate a listing of descriptive statistics.
>
> However the statistical tool to use should depend on the nature of the
> variable. (ie tab command for categorical variables and sum command for
> continuous variables)
>
> I am wondering if there is a stata command to identify the variable format,
> ie something which will generate a binary outcome like 1 if is it continuous
> variable and 0 if not.

Stata does not have the concept of continuous versus categorical
variable. However, you can define a categorical variable as containing
either only strings or only integers and having a limited number of
categories, and than create a Stata program that checks that. Below is
a quick stab at such a program:

*----------------- begin example ---------------------
clear all
program define iscat, rclass
	version 12.1
	syntax varname [if] [in], [ kmax(integer 20) ]
	
	marksample touse
	
	// check if string
	capture confirm string variable `varlist'
	if !_rc {
		return scalar iscat = 0
		exit
	}
	
	// check if intger
	capture assert mod(`varlist',1) == 0 if `touse'
	if _rc {
		return scalar iscat = 0
		exit
	}
	//check number of categories
	qui levelsof `varlist' if `touse'
	local k : word count `r(levels)'
	if `k' > `kmax' {
		return scalar iscat = 0
		exit
	}
	else {
		return scalar iscat = 1
		exit
	}
end

// try it out on some example data
sysuse auto

iscat rep78
return list

iscat mpg
return list

iscat foreign
return list

iscat headroom
return list

iscat make
return list
*------------------ end example ----------------------	
	
Hope this helps,
Maarten

--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany


http://www.maartenbuis.nl
--------------------------
*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index