Announcement

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

  • replacing subset of data

    Hi all

    I am new to Mata. Wondering what would be the Mata way (the fastest I suppose) of doing the following 'replace':


    Code:
    clear
    set obs 10
    g a=1
    g b=1
    g c=1
    g d=1
    g e=1
    g id=1 if _n>5
    
    foreach var of varlist a-e{
    replace `var'=. if id==1
    }

    Grateful for your help.

  • #2
    st_data() and st_store() have an argument called "selectvar" to select elements. Just make sure you replace with a matrix of the correct dimension. For your data
    Code:
    . replace id = _n > 5
    (5 real changes made)
    
    . mata n = sum(st_data(., "id"))
    
    . mata st_store(., 1..5, "id", J(n, 5, .))
    
    . list
    
         +------------------------+
         | a   b   c   d   e   id |
         |------------------------|
      1. | 1   1   1   1   1    0 |
      2. | 1   1   1   1   1    0 |
      3. | 1   1   1   1   1    0 |
      4. | 1   1   1   1   1    0 |
      5. | 1   1   1   1   1    0 |
         |------------------------|
      6. | .   .   .   .   .    1 |
      7. | .   .   .   .   .    1 |
      8. | .   .   .   .   .    1 |
      9. | .   .   .   .   .    1 |
     10. | .   .   .   .   .    1 |
         +------------------------+
    Note that I changed your id variable to take values 1 and 0 rather than 1 and missing, so it corresponds to true and false. I would also call id something else, like flag. Instead of hardcoding variables 1..5 you could define vars = ("a", "b", "c", "d", "e") and then code st_store(., vars, "id", J(n, length(vars), .)), which is more general.

    Comment


    • #3
      German Rodriguez thanks a lot!

      Comment

      Working...
      X