Stacking variables one below the other

廉价感情. 提交于 2020-01-30 07:26:10

问题


I have the following variables in my Stata dataset:

clear
input BGJTH98 GJKE54 SDKA12 JLTH65 VCNH58
2907 199 641 202 487
2908 199 641 202 487
2909 199 641 202 487
2910 199 641 202 487
2911 199 641 202 487
2912 199 641 202 487
2913 199 641 202 487
2914 199 641 202 487
2915 199 641 206 487
2916 199 641 202 487
2917 199 641 202 487
2918 199 641 202 487
2919 199 641 202 487
2920 204 641 202 487
2921 204 641 202 487
2922 204 641 202 487
2923 204 641 202 487
2924 204 641 202 487
2925 204 641 202 487
2926 204 641 202 487
2927 204 641 202 487
2928 204 641 202 487
2929 204 641 202 487
2930 204 641 202 487
2931 204 641 204 492
2932 204 641 204 492
2933 204 641 204 492
2934 204 641 204 492
2935 204 641 204 492
2936 204 641 204 492
end

I am trying to stack these variables one below the other but I do not get the results I expect:

stack *, into(a) clear

For example:

_stack   a  
   1   2907  
   1   2908  
   1   2909  
   1   2910  
   1   2911  

_stack  a  
   2   199  
   2   199  
   2   199  
   2   199  
   2   199  
   2   199  

However, what I would like is the output below:

_stack   a  
   1   2907  
   1    199  
   1    202  
   1    641  
   1    487  
   2   2908  
   2    199  
   2    202  
   2    641  
   2    487  

I would also like to save the variable names if possible.


回答1:


This is a problem best tackled with the reshape command:

rename (*) (a=)

generate _i = _n
reshape long a, i(_i) j(_j) string

list in 1/10

     +---------------------+
     | _i        _j      a |
     |---------------------|
  1. |  1   BGJTH98   2907 |
  2. |  1    GJKE54    199 |
  3. |  1    JLTH65    202 |
  4. |  1    SDKA12    641 |
  5. |  1    VCNH58    487 |
     |---------------------|
  6. |  2   BGJTH98   2908 |
  7. |  2    GJKE54    199 |
  8. |  2    JLTH65    202 |
  9. |  2    SDKA12    641 |
 10. |  2    VCNH58    487 |
     +---------------------+


来源:https://stackoverflow.com/questions/57660630/stacking-variables-one-below-the-other

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