(本文为andruw原创,转载请注明出处)
只要对Stata略有了解,恐怕一定知道reshape命令。它可以在“长”(long)、“宽”(wide)数据之间随意变换。本文并不想不厌其烦地介绍该命令的具体用法,因为对该命令的介绍网络上随处可见,而且help文档也有详尽的解释,并附有现成的例子。就算从未接触过该命令,也可照猫画虎不出二十分钟就跑出期待地结果。
一般而言,整理数据只需一次reshape命令即可。在非常不寻常的情况下,执行一次reshape是不够。本文就举一个需要两次reshape例子。
假设我们有如下数据:
- +----------------------------------------------------------------------+
- | country mode volume2011 volume2012 volume2013 volume2014 |
- |----------------------------------------------------------------------|
- 1. | China export 1000 2000 3000 4000 |
- 2. | China import 5000 6000 7000 8000 |
- 3. | UK export 9000 9100 9200 9300 |
- 4. | UK import 8000 8100 8200 8300 |
- 5. | Germany export 7000 7100 7200 7300 |
- 6. | Germany import 6000 6100 6200 6300 |
- +----------------------------------------------------------------------+
我们想要得到如下的长数据:
- +----------------------------------+
- | country year export import |
- |----------------------------------|
- 1. | China 2011 1000 5000 |
- 2. | China 2012 2000 6000 |
- 3. | China 2013 3000 7000 |
- 4. | China 2014 4000 8000 |
- 5. | Germany 2011 7000 6000 |
- 6. | Germany 2012 7100 6100 |
- 7. | Germany 2013 7200 6200 |
- 8. | Germany 2014 7300 6300 |
- 9. | UK 2011 9000 8000 |
- 10. | UK 2012 9100 8100 |
- 11. | UK 2013 9200 8200 |
- 12. | UK 2014 9300 8300 |
- +----------------------------------+
仔细观察数据,我们发现由于原始数据并非标准的“宽”数据,reshape一次是无法实现数据转换的。这种情况下就需要分两次reshape。第一次,reshape long命令,将volume转化为长数据;第二次,reshape wide,将mode转化宽数据。具体操作命令如下:
- clear
- input str16 country str16 mode volume2011 volume2012 volume2013 volume2014
- China export 1000 2000 3000 4000
- China import 5000 6000 7000 8000
- UK export 9000 9100 9200 9300
- UK import 8000 8100 8200 8300
- Germany export 7000 7100 7200 7300
- Germany import 6000 6100 6200 6300
- end
- reshape long volume, i(country mode) j(year) string
- reshape wide volume, i(country year) j(mode) string
- rename volume* *
本文的用意有二:(1)介绍一下reshape的trick;(2)Stata命令要活学活用。
Stata tips & tricks帖子列表:


雷达卡







京公网安备 11010802022788号







