rsubsetstata

Logical Subsetting in Mata


In Mata (the matrix language in Stata), I am trying to find logical subsetting or that's equivalent.

Consider that we have a matrix:

clear all

version 18
mata: tmp = (-0.5, 1 \ 5, -5)

Here, I want to replace positive and negative numbers with 1 and -1, respectively. (That is, in my problem, only signs matter)

So, the result I want is

       1    2
    +-----------+
  1 |  -1       |
  2 |   1   -1  |
    +-----------+

If I am using R, I may use logical subsetting like below:

tmp <- matrix(c(-0.5, 1, 5, -5), 2, 2, byrow = TRUE)

> tmp
     [,1] [,2]
[1,] -0.5    1
[2,]  1.0   -5

tmp[tmp > 0] <- 1
tmp[tmp < 0] <- -1

> tmp
     [,1] [,2]
[1,]   -1    1
[2,]    1   -1

But I cannot find how to do the same thing in Mata.


Solution

  • This is just a case for the sign() function.

    . mata
    ------------------------------------------------- mata (type end to exit) --------------------------------------------------------------
    : tmp = (-0.5, 1 \ 5, -5)
    
    : sign(tmp)
    [symmetric]
            1    2
        +-----------+
      1 |  -1       |
      2 |   1   -1  |
        +-----------+
    
    

    I am not an R expert but I'm confident at guessing that R has such a function too, so there's an equally direct solution.