Announcement

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

  • return variable number in a dataset

    Hi there
    I'm wondering if there's an easy way to determine a variable's number within a dataset.
    For example, if "gear_ratio" is the 11th variable in my dataset, is there a way to find that out easily?

    Code:
    sysuse auto, clear

  • #2
    Code:
     sysuse auto, clear
    (1978 automobile data)
    
    . mata : st_varindex("gear_ratio")
      11
    
    . mata : st_numscalar("where", st_varindex("gear_ratio"))
    
    . di scalar(where)
    11

    Comment


    • #3
      If you only want to know the number (position in the dataset):

      Code:
      describe gear_ratio , number
      If you want the number (position in the dataset) in a local macro, here are two ways:


      Code:
      sysuse auto
      
      // standard Stata
      preserve
      describe , replace clear
      levelsof position if name == "gear_ratio" , local(number)
      restore
      display "`number'"
      
      // Mata
      mata : st_local("number",strofreal((st_varindex("gear_ratio"))))
      display "`number'"

      Edit:

      The first (standard Stata) approach could be simplified to

      Code:
      preserve
      describe gear_ratio , replace clear
      local number = position
      restore
      Last edited by daniel klein; 17 Apr 2024, 04:33.

      Comment


      • #4
        Perfect, thank you both.

        Comment

        Working...
        X