Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: solution to my question: separating string of fixed length into sections


From   Michael McCulloch <[email protected]>
To   Statalist <[email protected]>
Subject   st: solution to my question: separating string of fixed length into sections
Date   Sat, 30 Dec 2006 10:44:15 -0800

I'd like to share what I learned (and thanks to Maarten Buis who suggested using -destring- in combination with the floor function.)

I have a date string which I'd like to convert to Stata date.

Before I can use mdy() and date(), I need to split the string into sections:
the first four characters for year,
then the next two for month,
then the last two for day.


. tostring datedx, replace
. generate str4 dxyr = substr(datedx,1,4)
. generate str2 dxmo = substr(datedx,5,6)
. generate str2 dxda = substr(datedx,7,8)
. destring dx*, replace
. gen edate = mdy(dxmo, dxda, dxyr)
. format edate %d
. list datedx edate dxyr dxmo dxda in 1/5
+-------------------------------------------+
| datedx edate dxyr dxmo dxda |
|-------------------------------------------|
1. | 19900417 17apr1990 1990 4 17 |
2. | 19880107 07jan1988 1988 1 7 |
3. | 19930407 07apr1993 1993 4 7 |
4. | 19880819 19aug1988 1988 8 19 |
5. | 19890127 27jan1989 1989 1 27 |
+-------------------------------------------+



AND, Maarten's suggestion for using -destring- in combination with the floor function:

You can achieve what you want by using the dates as numbers (i.e. use
-destring- first) in combination with the floor function. See the
example below:

.destring datedx, replace
.gen int year = floor(datedx/10000)
.gen int month = floor((datedx-year*10000)/100)
.gen int day = datedx - year*10000 - month*100
.list datedx year month day in 1/5
+-------------------------------+
| datedx year month day |
|-------------------------------|
1. | 19900417 1990 4 17 |
2. | 19880107 1988 1 7 |
3. | 19930407 1993 4 7 |
4. | 19880819 1988 8 19 |
5. | 19890127 1989 1 27 |
+-------------------------------+




Best wishes,
Michael


____________________________________

Michael McCulloch
Pine Street Clinic
Pine Street Foundation
124 Pine Street, San Anselmo, CA 94960-2674
tel 415.407.1357
fax 415.485.1065
email: [email protected]
web: www.pinest.org
www.pinestreetfoundation.org
www.medepi.net/meta





*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/




© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index