Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Generating distinct observations after expand


From   Aljar Meesters <aljar.meesters@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Generating distinct observations after expand
Date   Mon, 3 Jun 2013 17:29:17 +0200

Dear Stefan,

This will do the trick:

local n = 4 // n dummies

collapse d*,  by(id)
reshape long d, i(id) j(j)
forv i = 1 /`n'{
    bysort id : gen d`i' = ( _n == `i' & d == 1 )
}
drop if d == 0
drop d j

best,

Aljar

2013/6/3 Stefan Bernhard <stefanbernhard88@gmail.com>:
> Suppose there are an arbitrary number of dummy variables and n
> identical observations (after expand) for a number of individuals,
> where n can be different for each individual.
>
> I want to end up with n distinct observations per individual, where
> each observation has exactly one of the dummies with initial value 1
> kept at 1, while all others are set to 0, and the set of dummies must
> uniquely identify all observations within each individual.
>
> e.g.
>
> id | d1 d2 d3 d4
> 1 | 1 0 1 0
> 1 | 1 0 1 0
> 2 | 1 0 0 1
> 2 | 1 0 0 1
> 3 | 1 1 0 1
> 3 | 1 1 0 1
> 3 | 1 1 0 1
>
> I want to end up with
>
> id | d1 d2 d3 d4
> 1 | 1 0 0 0
> 1 | 0 0 1 0
> 2 | 1 0 0 0
> 2 | 0 0 0 1
> 3 | 1 0 0 0
> 3 | 0 1 0 0
> 3 | 0 0 0 1
>
> I have been trying around with while, foreach, macros, by: and whatnot
> for an hour now and can't find a way to do that.
>
> thanks, stefan bernhard,
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/faqs/resources/statalist-faq/
> *   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index