在 plm 包中将季度观察指定为时间索引的正确方法

Correct way to specify quarterly observations as the time index in the plm package

我正在尝试将存储在 data.table 中的季度数据转换为面板 data.frame 以准备进一步分析。但显然在使用季度日期作为时间维度时存在问题。 我可以将它们转换为日期、数字或字符,但它不被 is.pconsecutive() 识别为季度时间序列,这使我无法使用某些功能。

library(zoo)
library(data.table)
dt <- structure(list(Global.Company.Key = c(1380L, 1380L, 1380L, 1380L, 
1380L, 1380L, 1380L, 1380L), Calendar.Data.Year.and.Quarter = structure(c(2000, 
2000.25, 2000.5, 2000.75, 2001, 2001.25, 2001.5, 2001.75), class = "yearqtr"), 
    Calendar.Year.Quarter.Integer = c(10957L, 11048L, 11139L, 
    11231L, 11323L, 11413L, 11504L, 11596L), Year.Date = structure(c(10957, 
    11048, 11139, 11231, 11323, 11413, 11504, 11596), class = "Date")), .Names = c("Global.Company.Key", 
"Calendar.Data.Year.and.Quarter", "Calendar.Year.Quarter.Integer", 
"Year.Date"), row.names = c(NA, -8L), class = c("data.table", 
"data.frame"))
# defined the date index as integer
pdt <- pdata.frame(dt, index = c("Global.Company.Key", "Calendar.Year.Quarter.Integer"))
is.pconsecutive(pdt)
 1380 
 FALSE 

显然,时间维度是通过检查数据点之间的距离是否规则间隔和一来分析的。来自手册:"For evaluation of consecutiveness, the time dimension is interpreted to be numeric, and the data are tested for being a regularly spaced sequence with distance 1 between the time periods for each individual (for each individual the time dimension can be interpreted as sequence t, t+1, t+2, ... where t is an integer)." 那么转换年季度时间序列的最佳和最稳健的方法是什么?

我想出了一个解决问题的方法,它足以满足这个目的,并且只适用于这个特定的数据集,因为如果涵盖了不同的时间范围,它需要进行调整。 我基本上将所有季度相对于数据集中的第一季度进行转换,然后只计算每个季度的整数并将其用作时间索引。

library(lubridate)
dt[, Time.Index := (year(Calendar.Data.Year.and.Quarter)-2000)*4+quarter(Calendar.Data.Year.and.Quarter)]
pdt <- pdata.frame(dt , index = c("Global.Company.Key", "Time.Index"))
is.pconsecutive(pdt) # <- this then reports TRUE

这是一种解决方法,但我认为还不错。

pdata.frame 不知道季度数据,也不知道像 zoo 提供的设施包。将作为索引的变量强制转换为因子变量。

通过分析 is.pconsecutive 的作用:您需要一个时间变量作为索引,它是一个 "meaningful" 整数序列,先将因子强制转换为字符,然后再转换为数字(这就是 is.pconsecutive 确实如此)。

对于您的示例,您需要一个为此提供规则序列的索引: as.numeric(as.character(index(pdt)[[2]]))

对于您问题中的数据,您得到:

[1] 10957 11048 11139 11231 11323 11413 11504 11596,不计算为连续

对于您答案中的数据,您会得到:

[1] 1 2 3 4 5 6 7 8,判断为连续