Announcement

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

  • Adding suffix or prefix to each element of a global varlist

    Hello,

    I have a core set of variables and for each of them I generated several secondary variables. To keep my codes clean and short, I would like to define a global containing my core variables and then simply attach the relevant prefix or suffix.

    My suffix is "_OP" and I would like to attach it to all the elements of the global list1

    global list1 "x1 x2 x3 "
    tabstat ${list1}_OP, s(co me p50 min max v) columns(statistics) save

    Not sursprisingly, when running the code, Stata display "x1 ambigous abbreviation"

    Thank you very much in advance for your help.

  • #2
    On the evidence you give, this might work:

    Code:
    tabstat x?_OP
    with options to suit.

    General advice is to avoid the use of globals, as likely to be a source of bugs. I think it's several years since I defined any at all and I use Stata almost every day.

    Comment


    • #3
      Hi Nick

      Thank you for your message.

      Unfortunately the variables are called differently than the `x' I used in the example.
      In the end, I have used a foreach loop with a subinstr function to solve the issue. However, I will keep in mind your suggestion and warning about the bugs.

      Code:
      foreach x of global list1{
      global `x'_OP : subinstr global `x' " " " OP_", all

      Comment


      • #4
        Roberto Musmeci Did you find a solution to this problem? Was this the best solution?

        Comment


        • #5
          Endorsing Nick's advice in #2 to avoid globals, here's how to do it with a local macro:
          Code:
          local list1 x1 y2 abracadabra
          display `"`list1'"'
          
          local list1_OP: subinstr local list1 " " "_OP ", all
          local list1_OP `list1_OP'_OP
          display `"`list1_OP'"'
          If you really need to use a global macro instead, the code is almost the same. Substitute global for local and using $, with {} where needed, rather than `' for dereferencing. But, really, don't use a global unless there is no alternative. I've been using Stata pretty much daily since 1994 and only once found it necessary to resort to a global. (Even then, in retrospect, there were better alternatives, although a local would not have worked in that situation.)

          Comment

          Working...
          X