Announcement

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

  • if statement

    Suppose I have a variable var1. What is the best/most efficient way of accessing its contents in a Mata if statement?

    Something like:

    Code:
    ..... if var1 == 23

  • #2
    Belinda Foster It depends. Can you be more specific about your problem?

    One option is to use select or selectindex. Another is to use logical operators.
    Last edited by Christophe Kolodziejczyk; 11 Jun 2017, 11:19.

    Comment


    • #3
      I am trying to generate a random variable var2 for a specific value of var1. In Stata, this is straightforward:
      Code:
      gen var2=rbinomial(1, 0.46) if var1=23
      However, I need to do this in Mata. Any ideas?

      Comment


      • #4
        Belinda Foster IMHO an ifelse() function is lacking in Mata. There is a mm_cond() function in the moremata package, but it is slow.

        Code:
        mata:
        
        rseed(1)
        x = runiform(10,1):>.5
        var1 = 23*x
        
        either
        
        var2 = J(rows(var1),1,.)
        index = selectindex(var1:==23)
        var2[index] = rbinomial(rows(index),1,1,0.46)
        
        or
        
        var2 = rbinomial(rows(var1),1,1,0.46):*(var1:==23) // but here you evaluate more binomial variates than needed
        
        
        end

        Comment

        Working...
        X