Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Error in syntax: invalid syntax r(197)

    Dear Stata user,

    I wrote a simple systematic sampling command for Stata using Deepseek. I reviewed the code carefully and couldn't find any obvious errors. However, when I run it in Stata 16, it immediately throws an "invalid syntax" error. The problem seems to be centered on the syntax statement, but I really cannot figure out what violates Stata's syntax rules.

    I tried various adjustments: adjusting required and optional settings, changing the option types, such as replacing int with integer, and changing generate(str) to generate(name) – none of these solved the error. Strangely, when I change all optional options (enclosed in brackets) to required ones, the command runs without any issue. I am completely puzzled about what is going wrong here.

    I would greatly appreciate any help or suggestions you can offer. Thank you!

    Code:
    . systematicsample, samplesize(6)
    ------------------------------------------------------------------------------ begin systematicsample ---
    - version 15
    - syntax [if] [in] , SAMplesize(int) [GENerate(name) SEED(int) START(int) K(int) REPLACE]
    invalid syntax
    -------------------------------------------------------------------------------- end systematicsample ---
    r(197);
    Code:
    *! version 1.0.0  19Aug2026
    *! Systematic Sampling
    
    cap program drop systematicsample
    program define systematicsample, rclass
        version 15
    
        syntax [if] [in] , SAMplesize(int) [GENerate(name) SEED(int) START(int) K(int) REPLACE]
    
        * Check whether the sample size is positive
        if `samplesize' <= 0 {
            di as err "samplesize() must be an integer"
            exit 198
        }
    
        * Mark observations that meet the if/in conditions
        marksample touse
        qui count if `touse'
        local N = r(N)
    
        * Check the total sample size
        if `N' == 0 {
            di as err "Error: No observations meet the conditions"
            exit 2000
        }
        if `samplesize' > `N' {
            di as err "Error: Sample size cannot exceed the total number of observations"
            exit 198
        }
    
        * Handle random seed
        if "`seed'" != "" {
            set seed `seed'
            di as text "Random seed has been set to: `seed'"
        }
    
        * Calculate or verify the sampling interval k
        local k_auto = ceil(`N' / `samplesize')
        if "`k'" != "" {
            * User-specified k
            if `k' < 1 {
                di as err "Error: Sampling interval (k) must be a positive integer"
                exit 198
            }
            if `k' > `N' {
                di as text "Note: The specified sampling interval (k') is greater than the total sample size (N'), and will be automatically adjusted to `k_auto'"
                local k = `k_auto'
            }
            else {
                local k = `k'
            }
        }
        else {
            * Automatically calculate k
            local k = `k_auto'
            di as text "Automatically calculated sampling interval: k = ceil(`N' / `samplesize') = `k'"
        }
    
        * Handle random starting point
        local start_auto = ceil(`k' * runiform())
        if "`start'" != "" {
            * User-specified starting point
            if `start' < 1 | `start' > `k' {
                di as err "Error: Starting point (start()) must be between 1 and `k' (the sampling interval)"
                exit 198
            }
            local start = `start'
        }
        else {
            * Automatically generate random starting point
            local start = `start_auto'
            di as text "starting point: `start'"
        }
    
        * Generate indicator variable
        if "`generate'" == "" {
            local genvar "sample_flag"
            di as text "No variable name specified for generation; using default name: sample_flag"
        }
        else {
            local genvar "`generate'"
            * Check whether the variable name is valid
            cap confirm new var `genvar'
            if _rc {
                if "`replace'" == "" {
                    di as err "Error: Variable `genvar' already exists. Please use the replace option to overwrite, or specify a different variable name"
                    exit 198
                }
            }
        }
    
        * Perform sampling
        qui gen `genvar' = 0 if `touse'
        local j = `start'
        while `j' <= `N' {
            * Find the row number (actual observation number) of the j-th observation that meets the touse conditio
            local row = `j'
            * Directly mark using the observation sequence number
            qui replace `genvar' = 1 if `touse' & _n == `row'
            local j = `j' + `k'
        }
    
        * Check the actual sample size drawn
        qui count if `genvar' == 1
        local actual_sample = r(N)
    
        * Add variable label and value labels
        lab var `genvar' "Systematic sampling indicator (1=selected)"
        lab def `genvar' 0 "Not selected" 1 "Selected", replace
        lab val `genvar' `genvar'
    
        * Output summary information
        di as text "----------------------------------------"
        di as text "Systematic Sampling Results Summary"
        di as text "Total sample size (N): `N'"
        di as text "Target sample size: `samplesize'"
        di as text "Sampling interval (k): `k'"
        di as text "random start: `start'"
        di as text "Actual sample size drawn: `actual_sample'"
        if `actual_sample' != `samplesize' {
            di as text "Note: The actual number drawn (actual_sample') does not match the target value (samplesize') "
            di as text "because the end of the population does not complete a full interval"
        }
        di as text "mark variable: `genvar'"
        di as text "----------------------------------------"
    
        * return results
        return local genvar "`genvar'"
        return scalar N = `N'
        return scalar samplesize = `samplesize'
        return scalar k = `k'
        return scalar start = `start'
        return scalar actual = `actual_sample'
    end

  • #2
    Please read the help syntax carefully. For optional numeric options, you need to specify the default value taken if the user calls your command without those options.

    Comment


    • #3
      Thank you. But the problem does not lie here.

      Comment


      • #4
        Based on the error message you showed, the problem is that the row starting with syntax is invalidly defined. As you state, it works if all options are mandatory (i.e. defined without brackets). Mandatory options do not need default values as the user must always specify the actual values. However, non-mandatory options (i.e. those within brackets) are not necessarily defined by the user, thus a default value must be given somewhere. This is obtained by writing:

        [SEED(int 12345) START(int 0) K(int 0)]

        or whatever default values you consider plausible.
        This is the only difference between optional and mandatory options that result in this error message.

        Comment


        • #5
          Barna Szabo is correct.

          Code:
          help error
          leads to this key detail in [P] error

          197. invalid syntax
          This error is produced by syntax and other parsing commands when there is a syntax error in the use of the command
          itself rather than in what is being parsed.
          Chen and Barna both worked that out too.

          A challenging Stata quiz could have a cryptic question: Why is 197 not equal to 198?

          With my Stata code (and perhaps yours too) error 198 is by far the most common error code I see,

          Comment


          • #6
            Thank you so much Barna Szabo You are absolutely right, there it is the problem.

            Comment

            Working...
            X