Announcement

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

  • "recoding" a matrix

    Dear friends,
    I’m trying to recode a [r x k] matrix into a new [r x c] matrix of zeros and ones, where the ones are assigned based on conditions about the k columns of the initial matrix. For instance, given a [3x3] matrix [ 1, 0, 3 \ 0, 0, 0 \ 2, 4, 6 ] and the condition of a cell in a new [3x1] matrix being one (1) is that the three previous columns are different from zero for a given row. This would then render a new matrix [ 0 \ 0 \ 1].
    I don’t seem to find a “recode” type option for working with matrices. How can one do this? Can it be done in Stata? Or, it needs to be done in Mata?


  • #2
    Code:
    matrix orig = 1,0,3 \ 0,0,0 \ 2, 4,6
    mata: st_matrix("wanted",!rowsum(st_matrix("orig"):==0))
    matlist wanted
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Maarten,
      Thank you so much for your answer.
      What if the condition was that only one of the previous columns, rather than three, were zeros? Or one different condition for every possible combination of zeros or non-zeros in the three columns? The idea is to create a matrix that categorizes rows based on combinations of zero/non-zero of the three original columns..
      Thanks again !

      Comment


      • #4
        That is a very general question, so here is a very general answer: Yes you can do that, and you need to change the command I gave in #2 to do that. Just know that true in Stata is 1 and false is 0, rowsum adds the cells in a row, so it counts the number of trues, the exclamation mark is the not operator. Than work your way through the logic to get at the result you want.
        ---------------------------------
        Maarten L. Buis
        University of Konstanz
        Department of history and sociology
        box 40
        78457 Konstanz
        Germany
        http://www.maartenbuis.nl
        ---------------------------------

        Comment


        • #5
          Thanks again Maarten,
          I know the question is general, but your general answer is of great help to me. I'll work through it.

          Comment

          Working...
          X