Announcement

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

  • Names of st_tempname() temporal variables

    Hi everyone,

    In Mata, I am trying to work with temporary variables, but I am having trouble accesing them from Stata. For instance, if I use st_tempname() to create one temporary variable, "temp_var", the code works in creating the temporary variable, but I can't access it from Stata as `temp_var', only with the temporary name of the first variable, __000000.

    Code:
    sysuse auto, clear
    mata: st_addvar("double", temp_var=st_tempname())
    mata: st_store(.,temp_var, rnormal(74,1,10,100))
    
    summ __000000
    summ `temp_var'

    If I wanted to create even more temporary variables, st_tempname()'s documentation doesn't even mention how you can name them. For instance, here I create 11 temporary variables, and the only way to access them is with their names, __000000 to __00000A.

    Code:
    mata: idx=st_addvar("double", st_tempname(11))
    mata: st_store(.,idx, rnormal(74,11,10,100))
    summ __*
    How can I call these variables from Stata? Calling them as __0000* is not ideal, since after 10 variables the naming pattern changes to letters (__00000A), and these names will change if there are other temporary variables already defined.

  • #2
    Originally posted by Nicolas Suarez View Post
    In Mata, I am trying to work with temporary variables, but I am having trouble accesing them from Stata. . . .How can I call these variables from Stata?
    You get their names via the st_varname() function.

    Feed to that function the variable index vector that you get from st_addvar(), prepend any names that you want to them, and then send them to Stata in a local macro via the st_local() function.

    Like the following (I've limited it to three temporary variables instead of eleven for brevity).
    Code:
    version 18
    
    clear *
    
    set seed 1617787289
    
    quietly sysuse auto
    
    mata {
    
        Idxs = st_addvar("double", st_tempname(3))
        st_store(., Idxs, rnormal(st_nobs(), cols(Idxs), 10, 100))
    
        for (i=1; i<=cols(Idxs); i++) {
            st_local("temp_var" + strofreal(i), st_varname(Idxs[i]))
        }
    }
    
    display in smcl as result "`temp_var1'", "`temp_var2'", "`temp_var3'"
    
    forvalues i = 1/3 {
        summarize `temp_var`i''
    }
    
    exit

    Comment


    • #3
      Thank you Joseph, this is a great solution to my problem!

      Best,
      Nicolas.

      Comment

      Working...
      X