Announcement

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

  • Find unique elements of vector?

    Hi, I am wondering if a mata command exists for finding the unique values within a vector -- similar to R's unique command, where Au <- unique(A) returns a vector identical to A, but with all repeated values deleted. If for instance, I have A = [1 2 3 3 4 5 5 5 6 6 6 6], I would like the unique command to return a new vector [1 2 3 4 5 6 ]. (The ordering by value is specific to my situation, but of course A might more generally have values that repeat randomly across indices.)

    If no mata command exists (and I couldn't find one in the manual), I'd love tips on coding this up! Thanks in advance.

  • #2
    Mata has functions and not commands. Indeed, the same is true of R, roughly. Also, unique values occur once only; despite usages elsewhere distinct is arguably a better term for what you seek.

    Nevertheless, StataCorp doesn't feel obliged to follow my advice.

    Code:
    search unique Mata
    will point to a function uniqrows().

    Legal code would help here:

    Code:
    . mata
    ------------------------------------------------- mata (type end to exit) -------
    :  A = (1, 2, 3, 3, 4, 5, 5, 5, 6, 6, 6, 6)
    
    : uniqrows(A')
           1
        +-----+
      1 |  1  |
      2 |  2  |
      3 |  3  |
      4 |  4  |
      5 |  5  |
      6 |  6  |
        +-----+
    As the example shows, you will need to transpose a row vector first; equally you can transpose the result back if you wish.

    Comment


    • #3
      Hi Leah,

      The function you're looking for is uniqrows(). It pulls out the unique rows of a matrix, so if you have a column vector (as above) and you'd like the returned variable to be a column vector, you'll need to make use of transposition as in the following

      Code:
      mata:
      
      A = (1, 2, 3, 3, 4, 5, 5, 5, 6, 6, 6, 6)
      uniqrows(A')'
      
      end

      Comment


      • #4
        Thank you both, very much! Nick, quite right, command was the wrong term. I was stuck in stata-speak. : ) And good point about the transposing, though in this instance I was working with a column vector anyway. Thanks both again, I feel silly for missing that *function* in the mata manual.

        Comment

        Working...
        X