Announcement

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

  • Add local variable string to a string to call global variable in a loop

    Hi,

    I am experiencing a syntax problem. I would like to call a global variable base on a string create through a loop made up with several strings. I cannot get the syntax to call the global variable right. Would you be able to correct my mistake?

    Code:
    * Global variables I am trying to call
    global N_BUY_LNASCOMP=12
    global N_BUY_LS&PCOMP=5
    global N_BUY_LS&P600I=5
    global N_BUY_LDJCMP65=2
    
    foreach universe in "LS&PCOMP" "LDJCMP65" "LNASCOMP" "LS&P600I" {
        use http://www.stata-press.com/data/r9/autornd.dta, clear
        gen rank=_n
        keep rank
        
        * This is where I need help changing the ${N_BUY_"`universe'"} syntax
        keep if rank<=${N_BUY_"`universe'"}
    }
    Note that I am not seeking to replace global variables by local variables in the solution I am looking for. Thanks!






  • #2
    1) The ampersand (&) is not allowed in names
    2) Remove unnecessary (here all) double quotes

    Code:
    global N_BUY_LNASCOMP=12
    global N_BUY_LSPCOMP=5
    global N_BUY_LSP600I=5
    global N_BUY_LDJCMP65=2
    
    foreach universe in LSPCOMP LDJCMP65 LNASCOMP LSP600I {
        use http://www.stata-press.com/data/r9/autornd.dta, clear
        gen rank=_n
        keep rank
        keep if rank<=${N_BUY_`universe'}
    }
    Last edited by Bjarte Aagnes; 07 Aug 2020, 03:36.

    Comment


    • #3
      Francois Durant As already explained on 1 August in a previous thread you started, talking of "local variable" and "global variable" is talking in solecisms.

      It's a small deal but using Stata's terminology is a really good idea on Statalist. The terms to use are local macro and global macro. Otherwise you can confuse those who know less about Stata than you do and cause those who know more about Stata than you do to have to translate what you say to what you mean.

      On terminology what was said at https://www.stata.com/statalist/arch.../msg01258.html holds true with the additional warning that "global variable" now has quite a different meaning in Mata.

      Comment


      • #4
        Thanks a lot Bjarte, it really help!

        Got it Nick, will try pay attention to terminology next posts.

        Comment

        Working...
        X