Announcement

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

  • local containing a local

    Dear Statalist,

    Is it possible to transform the following code:

    Code:
    capture unab ``var'_id'cat : ``var'_id'cat_*
    if c(rc) == 111 {
        local ``var'_id'cat
    }
    
    capture unab ``var'_id'num : ``var'_id'num_*
    if c(rc) == 111 {
        local ``var'_id'num
    }
    
    
    capture unab ``var'_id'catprod : ``var'_id'catprod_*
    if c(rc) == 111 {
        local ``var'_id'catprod
    }
    
    capture unab hhcat : hhcat_*
    if c(rc) == 111 {
        local hhcat
    }
    
    capture unab hhnum : hhnum_*
    if c(rc) == 111 {
        local hhnum
    }
    Into the simpler :

    Code:
    foreach j of local groups {
        capture unab `j' : `j'_*
        if c(rc) == 111 {
            local `j'
        }
    }
    If it is, how can I define my local groups so that it contains the precise elements : ``var'_id'cat ``var'_id'num ``var'_id'catprod hhcat hhnum, without Stata referring to the content of the local macro ``var'_id' ? Thank you for your help.

  • #2
    Code:
    local group \`\`var'_id'cat \`\`var'_id'num \`\`var'_id'catprod

    Comment


    • #3
      Bjarte Aagnes answered your question, but personally I would advise against writing anything of the kind.

      Delaying macro evaluation in my experience is not needed and it is not in any sense helpful. A test of that is how easy you find it to explain that code to anyone wanting to know -- a student, a collaborator, a supervisor, a reviewer. Another test is how easily you can write or modify such code independently.

      At best it arises from a style of programming that is common and defensible in some languages -- that constants should be defined early in code. Early definition can be a good idea, but not like this.

      If that negative view seems dogmatic or patronising, please mark it first as personal opinion and then shoot me down, explaining why that is wrong.

      unab is great -- I even wrote a short puff for it at https://www.stata-journal.com/articl...article=dm0051 -- but here you're necessarily working around what is usually a feature, namely that unab complains if there is nothing to feed on.

      Another approach is shown by this example,


      Code:
      . sysuse auto, clear
      (1978 automobile data)
      
      . ds
      make          rep78         weight        displacement
      price         headroom      length        gear_ratio
      mpg           trunk         turn          foreign
      
      foreach g in m t a {
         capture unab `g' : `g'*
      }
      A check will show that local macro t is defined and contains trunk turn; similarly local macro m contains make mpg; while local macro a is empty (undefined).

      If I'm missing the point here, please explain why you need something different,

      Comment

      Working...
      X