Announcement

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

  • Unused option changes program behavior

    I'm writing a program which uses display to mimic a list command. The user can enter an optional variable list. The problem: If the option is specified, but not used, it affects the displayed result. Here's a minimal example in which the goal is to list the makes of the first three cars in the auto data set. Compare the second and third set of results.
    Code:
    clear
    program drop _all
    program define llist
        syntax varname  [, VARs(varlist min=1)]
       local listvar `1'
       tempvar id
       gen `id' = _n
       qui levelsof `id', local(ids)
       foreach i of local ids {
            di  `listvar'[`i']
            }
    end
    
    sysuse auto, clear
    keep in 1/3
    . list make
         +-------------+
         | make        |
         |-------------|
      1. | AMC Concord |
      2. | AMC Pacer   |
      3. | AMC Spirit  |
         +-------------+
    
    . llist make  
    AMC Concord
    AMC Pacer
    AMC Spirit
    
    . llist make, var(mpg)  
    AMC Concord 1
    AMC Concord 2
    AMC Concord 3
    Last edited by Steve Samuels; 03 Jun 2018, 08:15.
    Steve Samuels
    Statistical Consulting
    [email protected]

    Stata 14.2

  • #2
    Cannot tell why, but

    Code:
    display make,[1]
    is displayed as

    Code:
    AMC Concord 1
    I can tell why this happens. Steve uses syntax to parse user input but then still refers to positional arguments afterwards. When you type

    Code:
    llist make, var(mpg)
    local 1 is make, (note comma). The fix is simple: use local varlist instead of local 1.

    It would still be interesting to know why

    Code:
    display make,[1]
    is interpreted in the way shown here.

    Best
    Daniel

    Comment


    • #3
      help display:

      , displays one blank between two directives

      Code:
      . display make,[2]
      AMC Concord 2
      
      . display [2]
      2
      and ...
      Code:
      . display [2+2]*2
      8
      and
      Code:
      . scalar what = [2+2]*2
      
      . di what
      8
      
      . gen what = [2+2]*2
      
      . assert ( what == 8 )

      Comment


      • #4
        Thanks, Daniel! Changing
        Code:
        syntax varname
        to
        Code:
         syntax varlist(min=1 max=1)
        and changing "1" to "varlist" did the trick.
        Last edited by Steve Samuels; 03 Jun 2018, 09:26.
        Steve Samuels
        Statistical Consulting
        [email protected]

        Stata 14.2

        Comment


        • #5
          Bjarte Aagnes: Thanks for clarification.

          Steve Samuels: You can even stick to

          Code:
          syntax varname ...
          and still refer to `varlist'.

          Best
          Daniel

          Comment

          Working...
          X