Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How can these two datasets reshape between each other?

    Hi,

    I have two datasets linked below. Can anyone help me to reshape them between each other using STATA, please? Especially reshaping from the first pic to the second pic with only four variables. The most confusion for me is that I do not know how to let Stata identify Month variable in those variable names.

    Thank you!!

    Click image for larger version

Name:	Screen Shot 2019-01-12 at 6.43.52 PM.png
Views:	1
Size:	105.3 KB
ID:	1478734


    Click image for larger version

Name:	Screen Shot 2019-01-12 at 6.49.39 PM.png
Views:	1
Size:	196.3 KB
ID:	1478735

  • #2
    I've created a demonstration data set that is similar to what you are starting with.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str7 cityname float(ind_JAN_2000 ind_JAN_2001 ind_FEB_2000 ind_FEB_2001 ind_MAR_2000 ind_MAR_2001 ind_APR_2000 ind_APR_2001 ind_MAY_2000 ind_MAY_2001 ind_JUN_2000 ind_JUN_2001)
    "NY" 4 1 4 1 5 2 7 7 8 8 0 1
    "LA" 5 8 3 4 7 3 3 9 7 5 8 8
    "Chicago" 4 1 7 8 8 3 8 5 6 8 9 3
    end
    
    reshape long ind_, i(cityname) j(month_year) string
    gen mdate = monthly(month_year, "MY")
    assert missing(mdate) == missing(month_year)
    format mdate %tm
    drop month_year
    gen year = year(dofm(mdate))
    gen month = month(dofm(mdate))
    rename ind_ ind
    That said, for most purposes you will probably find separate variables for month and year difficult to work with. Unless you are going to do some modeling of month-based "seasonal" effects in your data, it will be easier to work with the variable mdate which combines the month and year into a single Stata monthly date variable.

    In the future, when showing data examples, please use the -dataex- command to do so. If you are running version 15.1 or a fully updated version 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    Comment


    • #3
      It works! Finally! Thank you so much for the code, Clyde!

      Comment

      Working...
      X