更新时间:2023-02-03 14:21:02
简而言之,你无法得到你想要的.这是因为在 R 中,数字形式的日期必须包含一天.
The short answer is that you can't get exactly what you want. This is because in R, dates with numeric form must include a day.
为了在 R 中成功导入 Stata 日期,您首先可以转换相应的Stata 中从每月到日期时间的变量:
For successfully importing a Stata date in R, you first can convert the respective variable in Stata from a monthly to a date-time one:
clear
set obs 1
generate date = monthly("2000-Jan", "YM")
display %tmCCYY-Mon date
2000-Jan
display date
480
replace date = dofm(date)
display %tdCCYY-Mon date
2000-Jan
display date
14610
replace date = cofd(date) + tc(00:00:35)
display %tc date
01jan2000 00:01:40
display %15.0f date
1262304100352
然后在 R 中您可以执行以下操作:
Then in R you can do the following:
statadatetime <- 1262304100352
rdatetime <- as.POSIXct(statadatetime/1000, origin = "1960-01-01")
rdatetime
[1] "2000-01-01 02:01:40 EET"
typeof(rdatetime)
[1] "double"
rdate <- as.Date(rdatetime)
rdate
[1] "2000-01-01"
typeof(rdate)
[1] "double"
您可以通过以下方式获得所需的年-(缩写)月形式:
You can get the Year-(abbreviated) Month form you want with the following:
rdate = format(rdate,"%Y-%b")
[1] "2000-Jan"
typeof(rdate)
[1] "character"
然而,正如你所看到的,这将改变 rdate
持有的类型日期.
However, as you can see, this will change the type of rdate
holding
the date.
尝试将其改回:
rdate <- as.Date(rdate)
Error in charToDate(x) :
character string is not in a standard unambiguous format