Search code examples
for-loopforeachstatastata-macrostabulate

Stata foreach loop says tabulate is not a valid command name?


Using Stata v18. I just want to tab all variables in the local varlist (in my original data, it's to display "missed" ER variables, but otherwise no difference). Any ideas on why Stata keeps telling me that

tab `var'

is not a valid command name?

I just want to tab all variables in the local varlist (percent frequencies for each variable in the list). Ultimately, I'm doing a larger loop splitting out the varlist by state, by caseworker, etc., but this is the KISS version.

I've replicated and traced my problem using example dataset nlsw88.dta:

clear
sysuse nlsw88.dta

set trace on
local varlist "married never_married grade collgrad south smsa c_city industry occupation union"
foreach var in `varlist' {
        tab `var'
        display "`var'"
    } 
set trace off

Stata repeatedly generates the following output and error message:

. clear

. sysuse nlsw88.dta
(NLSW, 1988 extract)

. 
. set trace on

. local varlist "married never_married grade collgrad south smsa c_city indu
> stry occupation union"

. foreach var in `varlist' {
  2.         tab `var'
  3.                 display "`var'"
  4.         } 
- foreach var in `varlist' {
= foreach var in married never_married grade collgrad south smsa c_city indu
> stry occupation union {
-      tab `var'
=      tab married
     is not a valid command name
  display "`var'"
  }
r(199);

end of do-file

r(199);

Any assistance appreciated.


Solution

  • Your code looks good in principle.

    I think Stata is objecting to an unusual character that has crept in to your code, or more than one.

    Notice that the error message you show us is NOT that tabulate (or tab) is not a valid command name. It is that

       is not a valid command name 
    

    Look for unusual characters before tabulate. Or just delete all the characters before tabulate and try again.

    Preparing code in MS Word is sometimes behind this problem. It is a word processor, not a text editor.

    All that said,

    sysuse nlsw88.dta, clear 
    
    tab1 married never_married grade collgrad south smsa c_city industry occupation union
    

    is a simple alternative to your loop.

    If you're checking for missing values in your real data, see

    help misstable 
    

    or the missings command from the Stata Journal, for which

    search dm0085, entry