Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: copy value within group


From   "Tim Wade" <[email protected]>
To   [email protected]
Subject   Re: st: copy value within group
Date   Mon, 23 Oct 2006 09:50:32 -0400

I usually use a different approach for these types of problems:

. input id x

           id          x
 1. 1 1
 2. 1 .
 3. 1 .
 4. 2 2
 5. 2 .
 6. 2 .
 7. 3 3
 8. 3 .
 9. 3 .
10. 3 .
11. 3 .
12. 4 4
13. 4 .
14. end

. qui bysort id (x): replace x=x[1]

. list

    +--------+
    | id   x |
    |--------|
 1. |  1   1 |
 2. |  1   1 |
 3. |  1   1 |
 4. |  2   2 |
 5. |  2   2 |
    |--------|
 6. |  2   2 |
 7. |  3   3 |
 8. |  3   3 |
 9. |  3   3 |
10. |  3   3 |
    |--------|
11. |  3   3 |
12. |  4   4 |
13. |  4   4 |
    +--------+



On 10/23/06, [email protected] <[email protected]> wrote:
frequently, yet I have never been happy about how I do it.  I've always
wondered if there was another way.

*Fact*: In my data there exists a variable, x, with the following
property (known by construction or verified with an -assert-).  Within
each group of observations identified by a unique id (call the variable
id), x is missing for all but one observation.

*Operation*: I want to assign the single nonmissing value of x to all
missing values of x within the group.  That is, when I'm done, x is
nonmissing for all observations and constant within id.  This  constant
value of x (within id) remains unchanged for the original nonmissing
values of x.

*My Solution*: Usually I accomplish this with something like:

bysort id: egen t = mean(x) //other -egen- commands work, like -max()-//
replace x = t drop t

*Comment*: This works because I choose an -egen- command that ignores
missing values.  What displeases me about this is that when I review my
code later, it is hard to tell what I'm really doing since my motivation
is not to compute a mean or max, per se, but just to execute
a sort of copy operation within group.  What would be nice is if there
were a command named copy() (or something clear) that (1) verified the
properties I require (see "Fact" above) and then (2) did the operation
I want (see "Operation" above).  Even a more transparent way of just doing
(2) (and not (1)) would be an improvement.  I'm not skilled enough to
easily write such a command.  Perhaps there is such a command or some
other way to do what I want that is more transparent than my solution.
Any suggestions?

Thanks.




*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index