2

所以这是我的麻烦:我想将一个长格式的数据文件改成宽格式。但是,我没有唯一的“j”变量;长格式文件中的每条记录都有几个关键变量。

例如,我想这样做:

| caseid | gender | age | relationship to respondent|
|---------------------------------------------------|
| 1234   |   F    | 89  | mother                    |
| 1234   |   F    | 10  | daughter                  |
| 1235   |   M    | 15  | cousin                    |
etc

并将其变成这样:

|caseid  | gender1 | age1 | rel1  |  gender2  | age2 | rel2    |
|--------------------------------------------------------------|
| 1234   | F       | 89   | mother| F         | 10   | daughter|
| 1235   | M       | 15   | cousin| .         | .    | .       |
etc

但是,数据缺少 reshape 命令所需的后缀变量。Stata有没有办法自动生成这个后缀?

4

1 回答 1

3

样本数据:

     +----------------------------------+
     | caseid   gender   age   relati~p |
     |----------------------------------|
  1. |   1234        F    89     mother |
  2. |   1234        F    10   daughter |
  3. |   1235        M    15     cousin |
  4. |   1235        F    14     sister |
  5. |   1235        F    55     mother |
     |----------------------------------|
  6. |   1236        M    32    brother |
  7. |   1236        M    68     father |
     +----------------------------------+

生成一个新的id:

. by caseid: gen newid = _n

给你这个:

     +------------------------------------------+
     | caseid   gender   age   relati~p   newid |
     |------------------------------------------|
  1. |   1234        F    89     mother       1 |
  2. |   1234        F    10   daughter       2 |
  3. |   1235        M    15     cousin       1 |
  4. |   1235        F    14     sister       2 |
  5. |   1235        F    55     mother       3 |
     |------------------------------------------|
  6. |   1236        M    32    brother       1 |
  7. |   1236        M    68     father       2 |
     +------------------------------------------+

你现在可以用这个重塑:

. reshape wide gender age relationship, i(caseid) j(newid)

要得到这个:

     +--------------------------------------------------------------------------------------------+
     | caseid   gender1   age1   relati~1   gender2   age2   relati~2   gender3   age3   relati~3 |
     |--------------------------------------------------------------------------------------------|
  1. |   1234         F     89     mother         F     10   daughter                .            |
  2. |   1235         M     15     cousin         F     14     sister         F     55     mother |
  3. |   1236         M     32    brother         M     68     father                .            |
     +--------------------------------------------------------------------------------------------+
于 2012-06-26T07:18:38.033 回答