Announcement

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

  • Sorting matrix including rownames

    Hi,
    I have a matrix that is stacked and would like to sort rows based on two of the variables. The matrix looks like this:

    Code:
    Variable    varorder     coeftype     number
    Adj_Age         1           1           5
    Adj_Age2        2           1          10
    Unadj_Age       1           2           7
    Unajd_Age2      2           2           9
    What I would like is the following:

    Code:
    Variable    varorder      coeftype     number
    Adj_Age         1           1           5
    Unadj_Age       1           2           7
    Adj_Age2        2           1          10
    Unajd_Age2      2           2           9
    i.e. sort on varorder then coeftype.

    I have tried Mata with the following code:

    Code:
    mata: rlabels = st_matrixrowstripe("full")
    mata: clabels = st_matrixcolstripe("full")
    
    mata : st_matrix("sorted", sort(st_matrix("full"), (1,2)))
    mata: _matrix_list(st_matrix("sorted"),rlabels,clabels)
    However, I can't sort the rlabels.

    Does anyone know how I can do this?

    Thanks.
    Last edited by Jane Fry; 18 May 2022, 19:48.

  • #2
    Here is one way

    Code:
    mata {
        colnames = st_matrixcolstripe("full")
        rownames = st_matrixrowstripe("full")
        order = order(st_matrix("full"), (1,2))
        st_matrix("full", st_matrix("full")[order,])
        st_matrixcolstripe("full", colnames)
        st_matrixrowstripe("full", rownames[order,])
    }

    EDIT

    If you were to do this more often, you could wrap this up into a Mata function

    Code:
    mata :
    
    void st_sort_matrix(
        string scalar    matname, 
        real   rowvector columns
        )
    {
        string matrix   rownames
        real  colvector sort_order
        
        rownames = st_matrixrowstripe(matname)
        
        sort_order = order(st_matrix(matname), columns)
        
        st_replacematrix(matname, st_matrix(matname)[sort_order,])
        
        st_matrixrowstripe(matname, rownames[sort_order,])
    }
    
    end
    You could then type

    Code:
    mata : sort_st_matrix("full", (1, 2))
    Probably someone has written something like that.
    Last edited by daniel klein; 19 May 2022, 00:07.

    Comment


    • #3
      Thank you Daniel. That's awesome!

      Comment

      Working...
      X