gpt4 book ai didi

date - 将日期变量,格式为 "JA11"转换为 Stata 中的日期

转载 作者:行者123 更新时间:2023-12-04 04:39:53 24 4
gpt4 key购买 nike

我有一个数据集,它有一个日期变量,现在是月份的两位字母缩写形式,后跟两位数字年份,例如 JA11 表示 2011 年 1 月。我如何将其转换为 Stata 可以识别为月/年日期?

数据结构示例:

.如果 _n<20,则列出 id1 ins HPR

    +--------------------+
| id1 ins HPR |
|--------------------|
1. | 1 AP11 1 YES |
2. | 1 AU11 1 YES |
3. | 1 DE11 1 YES |
4. | 1 FE11 1 YES |
5. | 1 JA11 1 YES |
|--------------------|
6. | 1 JL11 1 YES |
7. | 1 JU11 1 YES |
8. | 1 MA11 1 YES |
9. | 1 MY11 1 YES |
10. | 1 NO11 1 YES |
|--------------------|
11. | 1 OC11 1 YES |
12. | 1 SE11 1 YES |
13. | 2 AP11 2 NO |
14. | 2 AU11 2 NO |
15. | 2 DE11 2 NO |
|--------------------|
16. | 2 FE11 2 NO |
17. | 2 JA11 2 NO |
18. | 2 JL11 2 NO |
19. | 2 JU11 2 NO |
+--------------------+

.

谢谢你的帮助。

最佳答案

更新了您的示例数据:

gen month=substr(hp,1,2)
gen year=substr(hp,3,4)
replace year="2011" if year=="11" **you can omit this in your real data

您提供的数据不需要这部分。但是你可以在真实数据中使用
local yr "03 04 05 06 07 08 09 10 11"
local newyr "2003 2004 2004 2006 2007 2008 2009 2010 2011"
local n: word count `yr'
forvalues i=1/`n'{
local yr`i' : word `i' of `yr'
local newyr`i' : word `i' of `newyr'
bys ids: replace year="`newyr`i''" if year=="`yr`i''"
local i=`i'+1
}
local mon "JA FE MA AP MY JU JL AU SE OC NO DE"
local newmon "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC"
local n: word count `mon'

forvalues i=1/`n'{
local mon`i' : word `i' of `mon'
local newmon`i' : word `i' of `newmon'
bys ids: replace month="`newmon`i''" if month=="`mon`i''"
local i=`i'+1
}

egen datevar=concat(month year),punct(" ")
generate datevar1=date(datevar,"MY")
format datevar1 %d


ids hp month year datevar datevar1
1 AP11 APR 2011 APR 2011 01apr2011
1 AU11 AUG 2011 AUG 2011 01aug2011
1 DE11 DEC 2011 DEC 2011 01dec2011
1 FE11 FEB 2011 FEB 2011 01feb2011
1 JA11 JAN 2011 JAN 2011 01jan2011
1 JL11 JUL 2011 JUL 2011 01jul2011
1 JU11 JUN 2011 JUN 2011 01jun2011
1 MA11 MAR 2011 MAR 2011 01mar2011
1 MY11 MAY 2011 MAY 2011 01may2011
1 NO11 NOV 2011 NOV 2011 01nov2011
1 OC11 OCT 2011 OCT 2011 01oct2011
1 SE11 SEP 2011 SEP 2011 01sep2011
2 AP11 APR 2011 APR 2011 01apr2011
2 AU11 AUG 2011 AUG 2011 01aug2011
2 DE11 DEC 2011 DEC 2011 01dec2011
2 FE11 FEB 2011 FEB 2011 01feb2011
2 JA11 JAN 2011 JAN 2011 01jan2011
2 JL11 JUL 2011 JUL 2011 01jul2011
2 JU11 JUN 2011 JUN 2011 01jun2011

关于date - 将日期变量,格式为 "JA11"转换为 Stata 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19058331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com