循环的R年度

时间:2016-06-14 02:14:07

标签: r loops time-series regression

我希望循环使用年度季度的R数据框,并在每个季度进行滚动回归。然后,我使用此模型中的系数来拟合前一个季度的值。但是想在R中使用季度日期格式吗?

我有类似的问题 [Stata问题](Stata year-quarter for loop),但在R中重新审视它.R是否具有可以在循环中轻松使用的年度概念?例如,一个可能是圆的方式是

months.list <- c("03","06","09","12")
years.list <- c(1992:2007)

## Loop over the month and years
for(yidx in years.list)
{

  for(midx in months.list)
  {
  }
 }

我看到zoo :: package有一些功能,但不确定我可以使用哪一个特定于我的情况。以下几行中的一些内容是理想的:

for (yqidx in 1992Q1:2007Q4){
   z <- lm(y ~ x, data = mydata <= yqidx )
 }

当我向前看时,我需要交出它,以便在下一季度yqidx + 1上运行谓词值,因此2000Q4将移至2001Q1。

1 个答案:

答案 0 :(得分:0)

如果你需要帮助就是如何生成季度,

require(data.table)
require(zoo)
months.list <- c("03","06","09","12")
years.list <- c(1992:2007)
#The next line of code generates all the month-year combinations.
df<-expand.grid(year=years.list,month=months.list)
#Then, we paste together the year and month with a day so that we get dates like "2007-03-01".  Pass that to as.Date, and pass the result to as.yearqtr.
df$Date=as.yearqtr(as.Date(paste0(df$year,"-",df$month,"-01")))
df<-df[order(df$Date),]

然后你可以根据需要使用循环。我个人考虑使用data.table,如下所示:     需要(data.table)     需要(动物园)     DT&LT; -data.table(expand.grid(年= years.list,月= months.list))     DT&LT; -DT [顺序(年,月)]     DT [,日期:= as.yearqtr(as.Date(paste0(年, “ - ”,月, “ - 01”)))]

#Generate fake x values.

DT[,X:=rnorm(64)]

#Generate time index.

DT[,t:=1:64]

#Fake time index.

DT[,Y:=X+rnorm(64)+t]

#Get rid of the year and month columns -unneeded.

DT[,c("year","month"):=NULL]

#Create a second data.table to hold all your models.

Models<-data.table(Date=DT$Date,Index=1:64)

#Generate your (rolling) models.  I am assuming you want to use all past observations in each model.

Models[,Model:=list(list(lm(data=DT[1:Index],Y~X+t))),by=Index]

#You can access an individual model thusly:

Models[5,Model]