Statalist


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

RE: st: excluding variables by type


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   RE: st: excluding variables by type
Date   Tue, 25 Mar 2008 17:20:08 -0000

I often use Eva's method of calling up -ds-. It is convenient, if not
necessarily optimal. 

But using -ds- in the first example is unnecessary. Consider 

foreach x of varlist * {
   capture confirm string variable `x'
   if !_rc {
      do string things
   }
   else {
      do numeric things
   }
}

In the second example, I offer two small tweaks: 

1. r(varlist) is already suitable. There is no need to evaluate it, and
some loss in doing so, especially if the variable list is very long. 

2. Also, the -varlist- makes Stata do work that it has already done. (It
would go through the elements of the list to see if any were wildcards
and should be expanded, but that is not necessary. The elements are
guaranteed to be individual variable names.) 

The loops should thus begin 

foreach x in `r(varlist)' { 

or 

local vlist `r(varlist)' 
foreach x of local vlist { 

Nick
[email protected] 

Eva Poen

Libby,

here are two ways to do it.

1.
qui ds *
foreach x of varlist `=r(varlist)' {
   capture confirm string variable `x'
   if !_rc {
      do string things
   }
   else {
      do numeric things
   }
}

2.
qui ds *, has(type string)
foreach x of varlist `=r(varlist)' {
   do string things
}

qui ds *, has(type numeric)
foreach x of varlist `=r(varlist)' {
   do numeric things
}


2008/3/25, Libby Hemphill <[email protected]>:
>  I'm wondering if there's a way to loop through all my variables and
>  perform some action only on those that are numeric.  Is there a way
to
>  check for the type of the variable before doing something?  Like
>
>  for each variable
>  if string, next
>  else do X
>  end for

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   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