Announcement

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

  • Save names and scalar from a community-contributed command in a matrix

    Some community-contributed commands like xtoverid do not return a matrix of results similar to xtreg but sets of scalars, but I want to return them in a matrix with their names for easier referencing in a matrix after I have run a command and give the matrix a simple name. I know how to extract the scalars manually from this post OR how to automatically extract the names of the scalar from this post.

    Code:
    use https://www.stata-press.com/data/r18/union.dta, clear
    xtset idcode year
    xtreg union age black
    xtoverid
    
    * Matrix with the results
    matrix A = r(j) \r(jdf) \ r(jp)
    
    * Extract the scalar names
    local haus: r(scalars)
    Desired result would be a matrix like this, where the name of the matrix would be "hausmantest":
    stat
    j -294.19553
    jp 55.691719
    jdf -5.2825724
    __________________________________________________ __________

    Cheers, Felix
    Stata Version: MP 18.0
    OS: Windows 11

  • #2
    I figured that I need to write a little command myself. I have started to write the program but it does not work as intended. It returns nothing

    Code:
    capture program drop mtxextract
    program define mtxextract
        args name
        local scalarnames: r(scalars)
        local scalarcount: word count `scalars''
        matrix define m`name'
        matrix rownumber = `scalarcount'
        matrix rownames = `scalarnames'
        matrix colnames = stat
        foreach na of `scalarnames' {
            local i = 0
            matrix[i,1] = r(`na')
            i++
        }
    end
    Last edited by Felix Kaysers; 06 Mar 2024, 16:15.
    __________________________________________________ __________

    Cheers, Felix
    Stata Version: MP 18.0
    OS: Windows 11

    Comment


    • #3
      Here is a working version of a little program to extract the scalars from a command and put them into a matrix. Particularly useful when one wants to report the values directly in putdocx.

      Code:
      program define mtxextract
      args name
      local scalarnames: r(scalars)
      local scalarcount: word count `scalarnames'
      
      * Create a matrix to store the scalar values
      matrix `name' = J(`scalarcount', 1, .)
      matrix rownames `name' = `scalarnames'
      matrix colnames `name' = "stat"
      
      * Initialize the index
      local i = 1
      
      * Iterate over scalar names and assign their values to the matrix
      foreach na of local scalarnames {
      matrix `name'[`i', 1] = r(`na')
      local ++i
      }
      matrix list `name'
      end
      __________________________________________________ __________

      Cheers, Felix
      Stata Version: MP 18.0
      OS: Windows 11

      Comment

      Working...
      X