How to reshape long to wide data in Stata?

空扰寡人 提交于 2020-01-02 08:59:05

问题


I have the following data:

id      tests      testvalue
1       A           4
1       B           5
1       C           3
1       D           3 
2       A           3
2       B           3
3       C           3
3       D           4
4       A           3
4       B           5
4       A           1
4       B           3

I would like to change the above long data format into following wide data.

id      testA   testB    testC   testD   index
1       4      5        3         3        1
2       3      3        .         .        2
3       .      .        3         4        3
4       3      5        .         .        4
4       1      3        .         .        5

I am trying

reshape wide testvalue, i(id) j(tests) 

It gives error because there are no unique values within tests.

What would be the solution to this problem?


回答1:


You need to create an extra identifier to make replicates distinguishable.

clear 
input id  str1    tests      testvalue
1       A           4
1       B           5
1       C           3
1       D           3 
2       A           3
2       B           3
3       C           3
3       D           4
4       A           3
4       B           5
4       A           1
4       B           3
end 
bysort id tests: gen replicate = _n 
reshape wide testvalue, i(id replicate) j(tests) string 

See also here for documentation.



来源:https://stackoverflow.com/questions/28839986/how-to-reshape-long-to-wide-data-in-stata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!