How to reshape long to wide data in Stata?

2019-05-18 08:52发布

问题:

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.