Announcement

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

  • Within

    Hi all,

    I am trying to implement Mata code that creates an index within subgroups formed by the columns of a matrix. I have a matrix of the following form:

    Code:
           1   2
        +---------+
      1 |  2   3  |
      2 |  2   3  |
      3 |  2   4  |
      4 |  2   4  |
      5 |  3   5  |
      6 |  3   6  |
        +---------+
    The code should add a third column with the within-group index:

    Code:
           1    2   3
        +-------------+
      1 |  2   3   1  |
      2 |  2   3   2  |
      3 |  2   4   1  |
      4 |  2   4   2  |
      5 |  3   5   1  |
      6 |  3   6   1  |
        +-------------+
    In Stata, I would run the following code to create the index in a new variable.

    Code:
    sort g1 g2
    by g1 g2: gen id = _n
    I hope I made myself clear. Sorry if the topic came up somewhere else before.

  • #2
    Code:
    clear all
    mata
    foo = 1 \ 2 \ 1 \ 2 \2 \3 \4
    _sort(foo,1)
    
    bar = J(rows(foo),1,.)
    bar[1] = 1
    
    for (i = 2 ; i <= rows(bar) ; i++) {
        if (foo[i-1] == foo[i]) {
            bar[i] = bar[i-1] + 1
        }
        else {
            bar[i] = 1
        }
    }
    foo, bar
    end
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Hi Andreas,
      Maarten's approach works if your groups are identified by just one column. In your example with two columns, the following should work:
      Code:
      clear all
      mata
      G    = (2, 3 \ 2, 3 \ 2, 4 \ 2, 4 \ 3, 5 \ 3, 6)
      H    = uniqrows(G, 1)
      K    = J(0, 3, .)
      for (i = 1; i <= rows(H); i++) {
          K    = (K \ J(H[i, 3], 1, H[i, (1..2)]), (1::H[i, 3]))
      }
      K
      end
      Code:
      : K
             1   2   3
          +-------------+
        1 |  2   3   1  |
        2 |  2   3   2  |
        3 |  2   4   1  |
        4 |  2   4   2  |
        5 |  3   5   1  |
        6 |  3   6   1  |
          +-------------+
      https://twitter.com/Kripfganz

      Comment

      Working...
      X