Announcement

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

  • cumulative row sum?

    Dear all, The following question is taken from here (http://bbs.pinggu.org/forum.php?mod=...=1#pid50149617). The data is
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str13 comp_ctry float(rela_00 rela_01 rela_02 rela_03 rela_04 rela_05)
    "4401210001102" . 1 1 . . .
    "4401210001103" . 1 1 1 . .
    "4401210001106" . 1 1 . . .
    "4401210001107" 1 . 1 . . .
    "4401210001108" 1 . 1 1 . .
    "4401210001110" 1 1 1 1 1 .
    "4401210001111" 1 1 1 1 . .
    "4401210001112" 1 1 1 1 . .
    end
    The purpose is to obtain the cumulative frequencies across the columns for each row (comp_ctry). My answer is:
    Code:
    ren rela_(##) rela_20(##)
    ren rela_* yr*
    reshape long yr, i(comp_ctry) j(year)
    bys comp_ctry (year): gen n = sum(yr)
    replace n = . if yr == .
    drop yr
    reshape wide n, i(comp_ctry) j(year)
    ren n20(##) rela_(##)
    and the desired result is
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str13 comp_ctry float(rela_00 rela_01 rela_02 rela_03 rela_04 rela_05)
    "4401210001102" . 1 2 . . .
    "4401210001103" . 1 2 3 . .
    "4401210001106" . 1 2 . . .
    "4401210001107" 1 . 2 . . .
    "4401210001108" 1 . 2 3 . .
    "4401210001110" 1 2 3 4 5 .
    "4401210001111" 1 2 3 4 . .
    "4401210001112" 1 2 3 4 . .
    end
    My question is that: Is there a simple command that can calculate the cumulative frequencies for each row (comp_ctry)?
    Ho-Chuan (River) Huang
    Stata 19.0, MP(4)

  • #2
    I don't know of a way to do this with one command unless you write a program for the purpose. It's certainly possible to do it without a reshape.

    Code:
    gen work = 0 
    
    quietly forval j = 0/5 { 
        replace work = work + (rela_0`j' == 1) 
        replace rela_0`j' = work if rela_0`j' == 1 
    } 
    
    drop work
    But a reshape long looks a good idea, for reasons often aired in this forum.

    Comment


    • #3
      Dear Nick, Thanks for this helpful suggestion.

      Ho-Chuan (River) Huang
      Stata 19.0, MP(4)

      Comment

      Working...
      X