Announcement

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

  • collapsing multiple observation into 1 observation

    Dear all,

    As you can see in Dataset1, I have 4 different variables (i.e. cases, codes, pyr, lvl and p). I would like to put the different observations into one observation without losing any information and I want to put the different codes and p's into different columns. I've tried the command collapse but that did not work out well for the different codes. Can someone help me please?

    Dataset1:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input int(cases codes yr) str3 mid byte lvl int p
    123 345 2000 "C20" 5 1023
    123 345 2000 "D40" 5 4798
    123 345 2000 "G80" 5 6933
    end
    The result that I would like to have:
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input int(cases codes yr) str3(mid1 mid2 mid3) byte lvl int p_mid1 byte I int(p_mid2 p_mid3)
    123 345 2000 "C20" "D40" "G80" 5 1023 . 4798 6933
    end
    Thank you in advance!
    Last edited by Glenda C; 29 Apr 2017, 02:45.

  • #2
    An:
    it seems you should work through a combination of -collapse- and -merge-.
    -collapse- per se can't do the trick.
    Kind regards,
    Carlo
    (Stata 18.0 SE)

    Comment


    • #3
      You asked for this:
      Code:
      clear
      input int(cases codes yr) str3(mid1 mid2 mid3) byte lvl int p_mid1 byte I int(p_mid2 p_mid3)
      123 345 2000 "C20" "D40" "G80" 5 1023 . 4798 6933
      end
      
      . list, noobs
      
        +--------------------------------------------------------------------------------+
        | cases   codes     yr   mid1   mid2   mid3   lvl   p_mid1   I   p_mid2   p_mid3 |
        |--------------------------------------------------------------------------------|
        |   123     345   2000    C20    D40    G80     5     1023   .     4798     6933 |
        +--------------------------------------------------------------------------------+
      If you run the commands below on your initial data you get the same result.
      Code:
      ren p p_mid
      bysort cases codes yr: gen j = _n
      reshape wide mid lvl p_mid, i(cases codes yr) j(j)
      drop lvl2 lvl3
      ren lvl1 lvl
      gen I = .
      order cases codes yr mid* lvl p_mid1 I p_mid2 p_mid3
      
      . list, noobs
      
        +--------------------------------------------------------------------------------+
        | cases   codes     yr   mid1   mid2   mid3   lvl   p_mid1   I   p_mid2   p_mid3 |
        |--------------------------------------------------------------------------------|
        |   123     345   2000    C20    D40    G80     5     1023   .     4798     6933 |
        +--------------------------------------------------------------------------------+

      Comment


      • #4
        Thank you very much!

        Comment

        Working...
        X