本文介绍了将日期从 Stata 转换为 R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将整数向量转换为日期.

I am having difficulty converting a vector of integers into dates.

我使用以下方法从 Stata 导入了一个数据集:

I've imported a dataset from Stata using:

> dataire <- read.dta13("~/lcapm_ireland.dta", convert.factors = TRUE,
 generate.factors = FALSE, encoding = "UTF-8", fromEncoding = NULL,
convert.underscore = FALSE, missing.type = FALSE, convert.dates = TRUE,
replace.strl = TRUE, add.rownames = FALSE)

我的日期变量是从 2000 年 1 月开始的月度时间序列,格式为2000-Jan".

My date variable is a monthly time series starting on January 2000 and formatted as "2000-Jan".

与 R 类似,Stata 将日期作为整数处理,但在 1960 年 1 月后期,每月日期的原点为零.因此,当将数据集导入 R 时,我最终得到了以下形式的日期向量:

Similarly to R, Stata handles dates as integers but in the latter January 1960 is origin zero for monthly dates. Thus, when importing the dataset into R, I end up with a vector of dates of the form:

> c(478, 479, 480, ...)

另外,我的日期变量是:

In addition, my date variable is:

> class(datem)
[1] "Date"

如何使用 as.Date 或其他函数来转换格式为 "%Y-%b" 的每月日期变量中的整数时间序列?

How can I use as.Date or other functions to transform the time-series of integers in a monthly date variable formatted as "%Y-%b"?

推荐答案

简而言之,你无法得到你想要的.这是因为在 R 中,数字形式的日期必须包含一天.

The short answer is that you can't get exactly what you want. This is becausein 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 respectivevariable 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 holdingthe date.

尝试将其改回:

rdate <- as.Date(rdate)
Error in charToDate(x) :
  character string is not in a standard unambiguous format

这篇关于将日期从 Stata 转换为 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:59