Statalist


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

RE: st: Create a new variable based on some other variables


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   RE: st: Create a new variable based on some other variables
Date   Thu, 21 May 2009 11:39:34 +0100

Let's spell out that there is a difference between 

gen B = cond(A1 == 1, 1, cond(A2 == 3, 2, cond(A3 == 8, 3, 0))) 

and 

gen B=(A1==1)*1 + (A2==3)*2+(A3==8)*3

The order in -cond()- is crucial. Once for example observations with A1
== 1 are dealt with, they are not revisited, regardless of whether A2 ==
3 or A3 == 8 in the same observation. 

Nick 
[email protected] 

Martin Weiss

I thought about this case as well. If Charles wants the values for "B"
to 
accumulate, the solution is simply

***
gen B=(A1==1)*1+/*
*/(A2==3)*2+(A3==8)*3
***

From: "Nick Cox" <[email protected]>

> Thanks for the oblique compliment, but -cond()- is an official Stata
> function. My only indirect contribution, some while ago, was to
suggest
> it being generalised so that it could also produce string results.
>
> The article referred to by Martin Weiss at
> http://www.stata-journal.com/sjpdf.html?articlenum=pr0016
> was first-authored by David Kantor.
>
> However, there remains a problem with your specification. What happens
> (e.g.) if a1 is 1 AND a3 is 8?
>
> Nick
> [email protected]
>
> Charles Man@CCR
>
> Thanks to Martin and Eric for showing me how to do this and
introducing
> Dr Cox's -cond()- to me. Thanks a lot.
>
> From: "Eric A. Booth" <[email protected]>
>
>> gen b =.
>>  replace b=1 if a1==1
>>  replace b=2 if a2==3
>>  replace b=3 if a3==8
>
>>  On May 20, 2009, at 1:56 PM, Charles Man@CCR wrote:
>
>>  > If I want to create a new variable based on the values of a few
>>  > other variables, how can I do that?
>>  >
>>  > For instance,
>>  >
>>  > Create B
>>  > If A1=1, then B=1
>>  > If A2=3, then B=2
>>  > If A3=8, then B=3
>>  >
>>  > Can -gen- or -egen- or -recode- do this job?
>

*
*   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–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index