Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: foreach question

From   David Torres <>
Subject   Re: st: foreach question
Date   Sun, 22 Aug 2010 16:38:55 -0400

To complicate things a bit more, what if date1 and date2 and date3 and date4 represent, respectively, begin and end dates for employment.

Startjob1         Startjob2          Endjob1             Endjob2
01Jan1997         05June1997         24Dec1997          02Sept1997

Is there a way to sort both together so the correct start and end dates remain together? The data I am using are currently sorted on endjob dates, such that the most recent employment (i.e., at time of interview) is listed in job#1 slot. As you can see, however, sometimes a start date may precede another start date, while the end dates are actually reversed.

Thanks in advance.

Quoting Eric Booth <>:


I think this is what you are asking:

inp  str12(Date1          Date2         Date3         Date4)
23July1997    01Jan1997     12Sept1997     03Feb1997
05July1997	04July1997	03July1997	02July1997

foreach v in `r(varlist)' {
	g `v'2 = date(`v', "DMY")
	format `v'2 %td
	drop `v'
	rename `v'2 `v'
	g id = _n
reshape long Date, i(id) j(n)
sort Date
g new = _n
drop n id
g id = 1
reshape wide Date, i(id) j(new)
drop id

~ Eric
Eric A. Booth
Public Policy Research Institute
Texas A&M University
Office: +979.845.6754

On Aug 22, 2010, at 2:54 PM, David Torres wrote:

Is there a way to sort or reorder dates using the foreach command--perhaps using the egen function in the loop or something?

How do I get:

Date1          Date2         Date3         Date4

23July1997    01Jan1997     12Sept1997     03Feb1997

to be ordered thusly:

Date1          Date2         Date3         Date4
01Jan1997     03Feb1997     23July1997     12Sept1997


David Diego Torres

*   For searches and help try:

*   For searches and help try:

*   For searches and help try:

© Copyright 1996–2017 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index