Announcement

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

  • sum appears in the last row

    Dear All, I found this question here (http://bbs.pinggu.org/thread-6521515-1-1.html). The data is
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str8 area float(x1 x2 x3)
    "A" 1000 1200 2000
    "B"  800 1800  400
    "C" 2300 1230 2310
    end
    and I want to add another row, say "D", which value equals the total sum of each variable of x1-x3. Any suggestion is highly appreciated.
    Ho-Chuan (River) Huang
    Stata 17.0, MP(4)

  • #2
    Hi River,

    This seems like a strange thing to do to me. Why do you want to do it? There's probably a better way to solve your larger problem. Either way, here's code that does it:

    Code:
    set ob 4
    forval i=1/3{
    egen sum`i' = sum(x`i')
    replace x`i' = sum`i'[1] in `=_N'
    drop sum`i'
    }

    Comment


    • #3
      Here's an alternative using collapse and append

      Code:
      clear
      input str8 area float(x1 x2 x3)
      "A" 1000 1200 2000
      "B"  800 1800  400
      "C" 2300 1230 2310
      end
      
      preserve
      ds, has(type numeric)
      collapse `r(varlist)'
      save temp_collapse.dta, replace
      restore
      append using temp_collapse
      replace area="D" in `=_N'
      list
      Stata/MP 14.1 (64-bit x86-64)
      Revision 19 May 2016
      Win 8.1

      Comment


      • #4
        Let's spell it out. This is spreadsheet thinking. The downside of doing this is that you have to keep remembering to exclude the last observation from almost anything done later.

        That said: Here's another way to do it (you don't need to play with extra variables):

        Code:
        set obs 4
        forval i=1/3 {
            su x`i', meanonly
            replace x`i' = r(sum) in L
        }
        and two ways not to do it:

        Code:
        forval i=1/3 {
            su x`i', meanonly
        
            * #1  
            scalar x`i'_sum = r(sum)
        
            * #2
            gen x`i'_sum = r(sum)
        }
        Note that egen, sum() is undocumented as of Stata 9. It's more transparent to use egen, total() (but neither is needed here).
        Last edited by Nick Cox; 16 Jul 2018, 00:49.

        Comment


        • #5
          Thank you all for the helpful suggestions.
          Ho-Chuan (River) Huang
          Stata 17.0, MP(4)

          Comment

          Working...
          X