Warm tip: This article is reproduced from stackoverflow.com, please click
stata

Create table for asclogit and nlogit

发布于 2020-04-23 11:23:59

Suppose I have the following table:

id | car      | sex    | income
-------------------------------
1  | European | Male   | 45000
2  | Japanese | Female | 48000
3  | American | Male   | 53000

I would like to create the one below:

  | id | car      | choice | sex    | income
--------------------------------------------
1.| 1  | European | 1      | Male   | 45000
2.| 1  | American | 0      | Male   | 45000
3.| 1  | Japanese | 0      | Male   | 45000
  | ----------------------------------------
4.| 2  | European | 0      | Female | 48000
5.| 2  | American | 0      | Female | 48000
6.| 2  | Japanese | 1      | Female | 48000
  | ----------------------------------------
7.| 3  | European | 0      | Male   | 53000
8.| 3  | American | 1      | Male   | 53000
9.| 3  | Japanese | 0      | Male   | 53000

I would like to fit an asclogit and according to Example 1 in Stata's Manual, this table format seems necessary. However, i have not found a way to create this easily.

Questioner
Espie Rather
Viewed
28
Pearly Spencer 2018-05-29 07:15

You can use the cross command to generate all the possible combinations:

clear

input byte id str10 car str8 sex long income
1 "European" "Male"   45000
2 "Japanese" "Female" 48000
3 "American" "Male"   53000
end

generate choice = 0
save old, replace

keep id
save new, replace

use old
rename id =_0
cross using new

replace choice = 1 if id_0 == id
replace sex = cond(id == 2, "Female", "Male")
replace income = cond(id == 1, 45000, cond(id == 2, 48000, 53000))

Note that the use of the cond() function here is equivalent to:

replace sex = "Male"   if id == 1
replace sex = "Female" if id == 2
replace sex = "Male"   if id == 3

replace income = 45000 if id == 1
replace income = 48000 if id == 2
replace income = 53000 if id == 3

The above code snipped produces the desired output:

drop id_0
order id car choice sex income
sort id car

list, sepby(id)

     +------------------------------------------+
     | id        car   choice      sex   income |
     |------------------------------------------|
  1. |  1   American        0     Male    45000 |
  2. |  1   European        1     Male    45000 |
  3. |  1   Japanese        0     Male    45000 |
     |------------------------------------------|
  4. |  2   American        0   Female    48000 |
  5. |  2   European        0   Female    48000 |
  6. |  2   Japanese        1   Female    48000 |
     |------------------------------------------|
  7. |  3   American        1     Male    53000 |
  8. |  3   European        0     Male    53000 |
  9. |  3   Japanese        0     Male    53000 |
     +------------------------------------------+

For more information, type help cross and help cond() from Stata's command prompt.