r - 在 R 中后处理 Stata %tw 日期

标签 r date stata

Stata 中的 %tw 格式具有以下形式:1960w1,在 R 中没有等效格式。 因此必须对 %tw 日期进行后处理。

将 .dta 文件导入 R,日期是一个整数,如 1304(而不是 1985w5)或 1426(而不是 1987w23)。如果它是一个简单的时间序列,您可以按如下方式设置开始日期:

ts(df, start= c(1985,5), frequency=52) 

另一种可能性是:

as.Date(Camp$date, format= "%Yw%W" , origin = "1985w5") 

但是如果每一行不是一个单一的日期,那么你必须转换它。

包 ISOweek 基于 ISO-8601,格式为“1985-W05”,不处理 Stata %tw。

Lubridate 包不适用于这种格式。 week() 返回日期和 1 月 1 日之间发生的完整 7 天周期数加一。 week function

在 Stata 中,任何一年的第 1 周都从 1 月 1 日开始,无论是星期几。 Stata Documentation on Dates

在格式 %W of Date in R 中,一周从星期一开始,作为一周的第一天。

来自 strptime %V 是

the Week of the year as decimal number (00--53) as defined in ISO 8601. If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. (Accepted but ignored on input.) Strptime

Larmarange 在 Github 上指出 Haven doesn't interpret dates properly :

months, week, quarter and halfyear are specific format from Stata, respectively %tm, %tw, %tq and %th. I'm not sure that there are corresponding formats available in R. So far they are imported as integers.

有没有办法将 Stata %tw 转换为 R 可以理解的日期格式? Here is an Stata file with dates

最佳答案

这不会是 R 代码方面的答案,但它是 Stata 周的评论,无法放入评论中。

严格来说,Stata 中的日期由使它们易于人们理解的显示格式定义。 Stata 中的日期始终是一个数值变量或标量或宏定义,起源于 1960 年的第一个实例。因此它充其量只是谈论 %tw 日期等的简写。我们可以使用 display 来查看不同日期显示格式的效果:

. di %td 0
01jan1960

. di %tw 0
 1960w1

. di %tq 0
1960q1

. di %td 42
12feb1960

. di %tw 42
1960w43

. di %tq 42
1970q3

上面明确指出的一个微妙之处是,更改显示格式不会更改存储的内容,即数值。

换句话说,Stata 中的日期不是不同的数据类型;它们只是整数,通过相关的显示格式可以理解为日期。

问题的前提是用 Stata 周来描述一些每周的日期是正确的。这似乎不太可能,因为我不知道 StataCorp 之外的机构没有使用 Stata 的周规则的情况,不仅第 1 周总是从 1 月 1 日开始,而且第 52 周总是包括 8 或 9 天,因此有从来没有一个日历年的第 53 周。

因此,您需要向上游找出数据应该是什么。如果没有一些解释,我最好的建议是将每年的 52 周映射到开始它们的日子,即每个日历年的第 1(7)358 天。

Stata 周不会一对一映射到任何定义周的其他方案。

更多信息 this article on Stata weeks

关于r - 在 R 中后处理 Stata %tw 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32587055/

相关文章:

r - 将 ids -> items 转换为 {pairs of ids} -> items

python - 如何将 datetime.datetime 转换为 GMT 格式 python?

javascript - 在 JavaScript 中将本地日期和时间显示为年-月-日时-分-秒

syntax-error - reshape 长多个变量时出错

Stata:如何分隔本地宏的元素

ubuntu - 导出stata图和表失败

r - 尝试使用 R 过滤前 10 个条目?

删除列表中所有数据框中包含某个值的行

java - 在 Java 中将字符串转换为没有日期的时间

r - travis 构建失败,因为缺少 devtools