• Laura Whiting

Separating Dates by Specified Time Frame in Stata

A long timespan can be broken up into smaller time frames (eg years or months), and this may be necessary because a particular time period is of interest to you or because you are separating other data based on certain time periods. To facilitate this, in Stata you can create a loop that separates one variable into a number of variables based on the parameters the user provides. This can be used to create new variables containing only the dates the user wants. Below is an example of a list of dates separated by year in Stata.


Worked Example:

Stata records the date in two ways, either as the number of miliseconds since 12:00am 1 January 1960 (%tc), or the number of days since 1 January 1960 (%td). In this example, because I am not concerned with time, I will use the number of days version. I use the runiformint() function with the generate command to create a variable that contains numbers between 18,263 (1 January 2010) and 21,185 (1 January 2018).

In the command pane I type the following:

Which shows the following order of date variables:

Here you can see the dates have been separated into different variables depending on the year. The sort command has sorted each variable so the dates can be seen in ascending order across the table. From here you can focus in on one year by dropping all the other variables and observations. You could also combine some years into a single variable. Lets say I want to look at only the first 4 years from 2010 to 2013. In the command pane, I type the following:

This list command illustrates the change that has been made to the dataset:

Here you can see the 2011, 2012 and 2013 dates have been placed into the “y2010” variable, which we have renamed y10_13 to reflect this change. Finally, I might want to look at only the odd years, and I can do that by typing the following into the command pane:

Which shows the following with the list command:

Here you can see the y2011 variable now has dates from 2011, 2013, 2015 and 2017, all odd years. Depending on the list of dates you have, you can vary how you separate them. You could separate them into variables of different months, or biannually, or any time frame you choose.

0 views

© 2020 by Survey Design and Analysis Services. 

  • LinkedIn
  • Facebook
  • Twitter
  • YouTube