Reshape long with string split

I am trying to do a long long reshape on my data:

clear
input byte id float(v_az032_2017 v_az033_2017 v_az032_2018 v_az033_2018)
1 27.484943 27.324594  27.36449  27.32548
2  27.67231  27.32464 27.383556 27.325926
3 27.325935  27.32939 27.334106  27.32985
4  27.53663  27.32457   27.3705  27.33671
5 27.328493 27.325037 27.335546  27.33038
end

I have consulted the following pages but so far i have not been successful:

  1. Double reshape long
  2. Problems with reshape

How can i reshape my data to look like this:

id year   h      v  
 1 2017 az032 27.48494  
 1 2018 az032 27.36449  
 1 2017 az033 27.32459  
 1 2018 az033 27.32548  
 2 2017 az032 27.67231  
 2 2018 az032 27.38356  
 2 2017 az033 27.32464  
 2 2018 az033 27.32593 
728x90

1 Answers Reshape long with string split

Actually, you only need to reshape long once.

You can then simply split the resulting (composite) year variable and rename:

reshape long v_, i(id) j(az_year) string

split az_year, generate(var) parse("_")
drop az_year

rename v_ v
rename var1 h
rename var2 year

order id year h v

list, sepby(id)

     +------------------------------+
     | id   year       h          v |
     |------------------------------|
  1. |  1   2017   az032   27.48494 |
  2. |  1   2018   az032   27.36449 |
  3. |  1   2017   az033   27.32459 |
  4. |  1   2018   az033   27.32548 |
     |------------------------------|
  5. |  2   2017   az032   27.67231 |
  6. |  2   2018   az032   27.38356 |
  7. |  2   2017   az033   27.32464 |
  8. |  2   2018   az033   27.32593 |
     |------------------------------|
  9. |  3   2017   az032   27.32594 |
 10. |  3   2018   az032   27.33411 |
 11. |  3   2017   az033   27.32939 |
 12. |  3   2018   az033   27.32985 |
     |------------------------------|
 13. |  4   2017   az032   27.53663 |
 14. |  4   2018   az032    27.3705 |
 15. |  4   2017   az033   27.32457 |
 16. |  4   2018   az033   27.33671 |
     |------------------------------|
 17. |  5   2017   az032   27.32849 |
 18. |  5   2018   az032   27.33555 |
 19. |  5   2017   az033   27.32504 |
 20. |  5   2018   az033   27.33038 |
     +------------------------------+

4 months ago