Announcement

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

  • How to display names of tempvar?

    Dear all,
    I am using
    Code:
    tempvar
    variables in a program and I use them with
    Code:
    regress
    .
    I would like to see tempvar names, instead of __000001, in the regression output.
    How can I do?
    I past an example where I square the independent variables and then I use them in a regression.

    Thanks!
    Best,
    Raffaele

    Code:
    sysuse auto, clear
    
    capture program drop regsquare
    program regsquare
        syntax varlist
        gettoken depvar indepvars: varlist
        local sqvars
        foreach var of varlist `indepvars' {    
            tempvar `var' sq_`var'
            gen `sq_`var'' = `var'^2
            local sqvars `sqvars' `sq_`var''
        }
    
        regress `depvar' `indepvars' `sqvars'
    end
    
    regsquare price weight length

  • #2
    Stata's point of view is that it is showing variable names when it shows names like __000001. Local macro names such as sq_var used inside your program are utterly invisible outside your program. You need to solve this problem in some other way, e,g, doing more work inside your program to control display, or creating variables with new names inside a modified version of the dataset which you use only temporarily, or using factor variable notation.

    Comment


    • #3
      I would not use temporary variables, at least not for this specific problem. I would use factor variable notation.

      Code:
      sysuse auto, clear
      
      capture program drop regsquare
      program regsquare
          syntax varlist
          gettoken depvar indepvars: varlist
          local sqvars
          foreach var of varlist `indepvars' {    
              local sqvars `sqvars' c.`var'#c.`var'
          }
      
          regress `depvar' `indepvars' `sqvars'
      end
      
      regsquare price weight length
      Final output:

      Code:
      . regsquare price weight length
      
            Source |       SS       df       MS              Number of obs =      74
      -------------+------------------------------           F(  4,    69) =   21.16
             Model |   349888406     4  87472101.6           Prob > F      =  0.0000
          Residual |   285176990    69  4132999.85           R-squared     =  0.5509
      -------------+------------------------------           Adj R-squared =  0.5249
             Total |   635065396    73  8699525.97           Root MSE      =    2033
      
      -----------------------------------------------------------------------------------
                  price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
      ------------------+----------------------------------------------------------------
                 weight |  -20.55353   4.618585    -4.45   0.000    -29.76736   -11.33971
                 length |   1393.702   332.2459     4.19   0.000     730.8896    2056.514
                        |
      c.weight#c.weight |   .0039521   .0007089     5.58   0.000     .0025379    .0053663
                        |
      c.length#c.length |  -3.873754   .8738585    -4.43   0.000    -5.617055   -2.130454
                        |
                  _cons |  -93372.21   25814.06    -3.62   0.001    -144869.9   -41874.56
      -----------------------------------------------------------------------------------
      If you wanted to do something where factor variable notation would not work, I would probably use permanent names and then delete the vars I had created. You'd have to use names that do not already exist in the data set.
      -------------------------------------------
      Richard Williams
      Professor Emeritus of Sociology
      University of Notre Dame
      StataNow Version: 19.5 MP (2 processor)

      EMAIL: [email protected]
      WWW: https://academicweb.nd.edu/~rwilliam/

      Comment


      • #4
        Thank you very much Nick.

        Therefore a solution could be use 'real' variables instead of tempvars and drop them at the end of the program?

        Comment


        • #5
          Thanks to both!

          Comment


          • #6
            #4: Yes, that was one of the possibilities I mentioned. I'd go with factor variable notation here.

            Comment


            • #7
              I have been wrestling with a seemingly simple but surprisingly persistent issue regarding the use of temporary variables (tempvar) in Stata programming, and I hope to get some clarity from the community.

              I am currently developing a Stata program that performs several intermediate calculations. To keep the code clean and avoid conflicts with user data, I rely heavily on tempvar to create variables such as stdvalues, pagemissing, and indexofint. These temporary variables work perfectly for internal computations. However, I have run into a significant obstacle when it comes to debugging and providing informative output to the user.

              During the program's execution, I would like to use summarize on these temporary variables to give the user (or myself, during development) a sense of the data's distribution at key intermediate steps. The problem is that when I run summarize on a tempvar, Stata always displays its automatically generated name, which appears as something like __000001, __000002, and so on. This makes the output nearly useless for anyone trying to understand what is actually being summarized.

              I have tried several approaches to work around this. I attempted to assign the tempvar to a local macro with a descriptive name, like local stdvalues "values", and then use that macro in summarize. However, as I learned, this will generate a real variable in my dateset.

              This leads me to my core questions:

              (1) Is there any fundamental limitation in Stata that prevents tempvar from being displayed with a user-friendly alias in commands like summarize?

              (2) Are there any established programming patterns or best practices to achieve a more readable output for intermediate tempvar results? For instance, is there a way to temporarily "label" a tempvar or modify the output of summarize without abandoning the safety of using tempvar?

              (3) I have observed that many user-written Stata commands display clear, descriptive variable names in their output. Do these commands simply avoid tempvar entirely and rely on conventional variables that are later dropped, or is there a more sophisticated technique I am missing?

              Thank you in advance for your insights. I am eager to learn how experienced Stata programmers handle this common challenge. Any advice, code snippets, or references to relevant discussions or documentation would be greatly appreciated.

              Code:
              tempvar stdvalues pagemissing indexofint
              quietly gen `stdvalues'=0 if `touse'
              quietly gen `pagemissing'=0 if `touse'
              quietly gen `indexofint'=0 if `touse'

              Comment


              • #8
                Not sure whether I understand the problem correctly, but why not use label variable? See:
                Code:
                cap program drop foo
                program foo
                
                   syntax varlist(max=1) [if]
                   marksample touse
                   
                   tempvar stdvalues pagemissing indexofint
                   quietly gen `stdvalues'=0 if `touse'
                   lab var `stdvalues' "standardvalues"
                   quietly gen `pagemissing'=0 if `touse'
                   lab var `pagemissing' "pagemissing"
                   quietly gen `indexofint'=0 if `touse'
                   lab var `indexofint' "indexofint"
                   
                   di _n "Temporary variables 1:"
                   tab1 `stdvalues' `pagemissing' `indexofint'
                
                   qui ds, has(type byte int long)
                   qui replace `indexofint' = strpos("`r(varlist)'","`varlist'")
                   di _n "Temporary variables with variable `varlist':"
                   tab1 `indexofint'
                   
                end
                * ==============================================================================
                
                cls
                sysuse auto, clear
                
                foo rep78 if foreign==0
                foo headroom if foreign==0
                This will result in:
                Code:
                . foo rep78 if foreign==0
                
                Temporary variables 1:
                
                -> tabulation of __000002  
                
                standardval |
                        ues |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         48      100.00      100.00
                ------------+-----------------------------------
                      Total |         48      100.00
                
                -> tabulation of __000003  
                
                pagemissing |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         48      100.00      100.00
                ------------+-----------------------------------
                      Total |         48      100.00
                
                -> tabulation of __000004  
                
                 indexofint |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         48      100.00      100.00
                ------------+-----------------------------------
                      Total |         48      100.00
                
                Temporary variables with variable rep78:
                
                -> tabulation of __000004  
                
                 indexofint |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                         11 |         74      100.00      100.00
                ------------+-----------------------------------
                      Total |         74      100.00
                
                . foo headroom if foreign==0   
                
                Temporary variables 1:
                
                -> tabulation of __000002  
                
                standardval |
                        ues |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         52      100.00      100.00
                ------------+-----------------------------------
                      Total |         52      100.00
                
                -> tabulation of __000003  
                
                pagemissing |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         52      100.00      100.00
                ------------+-----------------------------------
                      Total |         52      100.00
                
                -> tabulation of __000004  
                
                 indexofint |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         52      100.00      100.00
                ------------+-----------------------------------
                      Total |         52      100.00
                
                Temporary variables with variable headroom:
                
                -> tabulation of __000004  
                
                 indexofint |      Freq.     Percent        Cum.
                ------------+-----------------------------------
                          0 |         74      100.00      100.00
                ------------+-----------------------------------
                      Total |         74      100.00
                But be ware that saving temporary variables may be dangerous, see here.

                Comment


                • #9
                  Or answering your question more directly:
                  Code:
                  cap program drop foo
                  program foo
                  
                     syntax varlist(max=1) [if]
                     marksample touse
                     
                     tempvar stdvalues pagemissing indexofint
                     quietly gen `stdvalues'=0 if `touse'
                     lab var `stdvalues' "standardvalues"
                     quietly gen `pagemissing'=0 if `touse'
                     lab var `pagemissing' "pagemissing"
                     quietly gen `indexofint'=0 if `touse'
                     lab var `indexofint' "indexofint"
                     
                     // Display names of tempvars:
                     foreach v of varlist `stdvalues' `pagemissing' `indexofint' {
                        di _n as res "tempvar `v' = `: variable label `v''"      
                     }
                     
                  end
                  * ==============================================================================
                  
                  cls
                  sysuse auto, clear
                  
                  foo rep78
                  results in
                  Code:
                  . sysuse auto, clear
                  (1978 automobile data)
                  
                  . 
                  . foo rep78
                  
                  tempvar __000002 = standardvalues
                  
                  tempvar __000003 = pagemissing
                  
                  tempvar __000004 = indexofint

                  Comment


                  • #10
                    That's quite a challenging series of questions in #7. I agree with Dirk Enzmann : the main point as I see it is to use variable labels. Whether you apply them to those temporary variables -- or just ensure that the original variable labels are shown otherwise -- is secondary. (If the original variable did not have a variable label, use the variable name instead: that is a detail easy to overlook.)

                    Most Stata graph commands will use variable labels for graph axes if they have been defined, as will many tabulation commands. A specific trick for list is to define characteristics. Although the primary purpose of list is to list the original data, nothing stops you using it for temporary variables containing results. I often do that within programs.

                    Clearly the bottom line is that no one wants to see a display of __000042 or whatever the temporary name is.

                    Comment


                    • #11
                      Thank you so much Dirk Enzmann. In my practical work, I have to use those tempvar in summarize task. And whether I label them or not, the results give by summarize make no difference. For example,
                      Code:
                      cap program drop foo
                      program foo
                      
                         syntax varlist(max=1) [if]
                         marksample touse
                         
                         tempvar stdvalues pagemissing indexofint
                      
                         quietly gen `stdvalues'=runiform(0,.99)
                         lab var `stdvalues' "standardvalues"
                         quietly gen `pagemissing'=runiform(0,.99)
                         lab var `pagemissing' "pagemissing"
                         quietly gen `indexofint'=runiform(0,.99)
                         lab var `indexofint' "indexofint"
                      
                         summarize `stdvalues' `pagemissing' `indexofint'
                      
                       end
                      Code:
                      . foo rep78
                      
                          Variable |        Obs        Mean    Std. Dev.       Min        Max
                      -------------+---------------------------------------------------------
                          __000001 |         74    .4619932     .294415   .0279719   .9519876
                          __000002 |         74    .4834352    .2935481   .0019187   .9792597
                          __000003 |         74    .5263808    .2929939   .0123073   .9797978

                      Comment


                      • #12
                        This is not a fabrication on my part, but a real problem I encountered in my actual work. I used the -speedergles- command written by Joss Roßmann (available from SSC). Because the code uses temporary variables (tempvar) that cannot be given meaningful names, whenever I needed to summarize these temporary variables, the output would display those cryptic, mysterious variable names like __000003. Unless you dig into the code itself, it is impossible to decipher what they actually represent. Of course, -speedergles- was specifically designed for GLES data, so the "insiders" who are familiar with the project can easily understand what these temporary variables mean. For outsiders, however, it is a different story. (NOTE: -numdate- was wrote by Nick Cox, also from SSC. Actually, you can find any time variables to mimic the following example.)

                        Code:
                        . numdate clock start=V9, pattern(YMDhms)
                        (230 missing values generated)
                        
                        . numdate clock end=V10, pattern(YMDhms)
                        (395 missing values generated)
                        
                        . destring V19, gen(timeuse)
                        V19: all characters numeric; timeuse generated as double
                        
                        . speedergles start end, duration(timeuse) index(speedindex) flag(speeder)
                        
                            Variable |        Obs        Mean    Std. Dev.       Min        Max
                        -------------+---------------------------------------------------------
                            __000002 |      3,270    .9998781    .0005398   .9991285   1.001429
                        
                            Variable |        Obs        Mean    Std. Dev.       Min        Max
                        -------------+---------------------------------------------------------
                            __000002 |      3,105     .999878    .0005396   .9991202   1.001421
                        
                            Variable |        Obs        Mean    Std. Dev.       Min        Max
                        -------------+---------------------------------------------------------
                            __000003 |      3,500    1.821429    .5274388          0          2
                            __000004 |      3,270    .9998742    .0005396   .9991243   1.001425
                          speedindex |      3,270     .998134    .1832632   .4995843   1.499383
                             speeder |      3,270          .1    .3000459          0          1

                        Comment


                        • #13
                          PS: I have read through the code, so I already know what these temporary variables represent. Moreover, I have added comment outputs to the code itself, so that each time it runs, it displays what these temporary variables stand for. However, my ultimate goal is, of course, to go a step further and completely "externalize" these temporary variables—that is, to make their names and meanings visible and interpretable without having to refer back to the code or the comment itself.

                          Comment


                          • #14
                            If you know what the temporary variables stand for, you can use clonevar and create "normal" variables. In that way you can save the data also and avoid saving temporary variables (as I said, this can be dangerous). However, make sure that the variables created by clonevar don't exist, e.g. by preceding the clonevar command by cap drop <cloned_var> .

                            Comment


                            • #15
                              Thank you very much Dirk Enzmann

                              Comment

                              Working...
                              X