Announcement

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

  • Elegant way to sum contents of a single row vector?

    Is there a more elegant way to sum the contents of a row for subsequent computation? (It should not be necessary to make a call to mata to do this).

    Code:
    tabstat EARNINGS S EXP, stat(var) save
    
       stats |  EARNINGS         S       EXP
    ---------+------------------------------
    variance |  140.9398   7.52309  8.552562
    ----------------------------------------
    
    
    scalar foo = r(StatTotal)[1,1] + r(StatTotal)[1,2] + r(StatTotal)[1,3]
    display foo
    157.01546

  • #2
    Elegance is in the eye of the beholder, but:

    Code:
    sysuse auto, clear
    
    local vbles price mpg headroom trunk
    local nvbles: word count `vbles'
    
    matrix J = J(`nvbles', 1, 1)
    
    tabstat `vbles', stat(var) save
    matrix R = r(StatTotal) * J
    scalar foo = R[1,1]
    display foo
    Or, perhaps more elegant, if a tad opaque:
    Code:
    tabstat `vbles', stat(var) save
    matrix R = diag(r(StatTotal))
    scalar foo = trace(R)
    display foo

    Comment


    • #3
      Thank you - I do like the opaque version

      Comment


      • #4
        The first idea that Clyde showed can be shortened a bit:

        Code:
        . sysuse auto, clear
        (1978 Automobile Data)
        
        . tabstat price mpg headroom trunk, stat(var) save
        
           stats |     price       mpg  headroom     trunk
        ---------+----------------------------------------
        variance |   8699526  33.47205  .7157071  18.29619
        --------------------------------------------------
        
        . mat Sum = r(StatTotal)*J(colsof(r(StatTotal)),1,1)
        
        . mat list Sum
        
        symmetric Sum[1,1]
                         c1
        variance  8699578.5

        Comment

        Working...
        X