Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

Re: st: RE: generate new variables using the first record of the group (in statalist-digest V4 #5050)


From   Nick Cox <njcoxstata@gmail.com>
To   "statalist@hsphsun2.harvard.edu" <statalist@hsphsun2.harvard.edu>
Subject   Re: st: RE: generate new variables using the first record of the group (in statalist-digest V4 #5050)
Date   Wed, 30 Oct 2013 11:16:28 +0000

Allan's reference is to a thread starting at

http://www.stata.com/statalist/archive/2013-10/msg01027.html

(Statalist digest references are not usable by anybody getting the
list message by message.)

Despite the title of the thread, Lin Song's question was not about
doing things separately by group. But as Allan has raised the
question, note that  his code

sort groupvar /* if not already done */
by groupvar: gen rowno = _n
gen chosenval = x if rowno == 1 /* or any other value */

is equivalent to

bysort groupvar : gen chosenvalue = x if _n == 1

so that the variable -rowno- does no harm but is dispensable.
Nick
njcoxstata@gmail.com


On 30 October 2013 10:26, Allan Reese (Cefas) <allan.reese@cefas.co.uk> wrote:
>>How do I generate a new variable with its value for all observations equals to the first observation or the nth observation of >another variable? [in groups according to the subj]
>
> Stata has a system variable to number cases. If the data are sorted, this can be restarted in each group. Having flagged the nth observation in each group, you can copy it. If there are more than one groups, you then have to split off each value, and maybe someone can think of another way to spread each selected value across all obs - if that is what is wanted.
>
>    sort groupvar /* if not already done */
>    by groupvar: gen rowno = _n
>    gen chosenval = x if rowno == 1  /* or any other value */
>    separate  chosenval, by(groupvar) g(cv)
>    egen allcv1 = max(cv1)  /* etc, or might be automated in a loop */
>
> Allan
>
>
>
>
>
> *
> *   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index