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 on April 23, and its replacement, statalist.org is already up and running.


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

Re: st: generate


From   "Dimitriy V. Masterov" <dvmaster@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: generate
Date   Wed, 6 Oct 2010 16:55:51 -0400

Mirriam Gee wants to:
> generate new variable(s) X1- X20 which contains the first 20
> numbers ( excluding the zeros) from g1- g100?. For example:

There's probably a more elegant way of doing this, but this can be
accomplished with the -reshape- command to make your data easier to
work with, and then reshaping it again to get it like you want it for
your analysis. First, preserve the data and then reshape long to get
the X variable. Then, reshape wide and save the X variables. Restore
the G variables data, and merge the Xs back in with the Gs:

#delimit;
/* Preserve your data */
preserve;

/* Preserve your data */
preserve;

/* Create the x variables with 2 reshapes */
keep hid g*;
reshape long g, i(hid) j(which_g);

drop if g==0;
rename g x;
bys hid: gen t=_n;
drop which_g;

reshape wide x, i(hid) j(t);

tempfile temp;
save "`temp'";

/* Restore data */
restore;

/* Merge the x variables with the g variables */
merge 1:1 hid using "`temp'";
drop x21-_merge;
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


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