2016-06-14 18 views
0

私は、年の四半期にある自分のRデータフレームをループし、毎年四半期に渡ってローリング回帰を実行したいと考えています。次に、このモデルの係数を使用して、1/4よりも前の値に適合させます。しかし、Rで四半期の日付形式を使用したいですか?R for inループ

[Stata question](Stata year-quarter for loop)と同様の問題がありましたが、Rで再訪しました。Rには、ループで簡単に使用できる年四半期の概念はありますか?例えばのために、方法について1つの、おそらくラウンドが

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) 
    { 
    } 
} 

は私が動物園::パッケージにはいくつかの機能を持って見るが、私はそれが私の場合に固有のもので使用できるかわからないです。私は先読みを行うと断定値はyqidx + 1である次の四半期上で実行されるように

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

が、私はそれを手に必要があり、そう2000Q4:次の行に沿っていくつかの事が理想的です2001Q1に移行します。

+0

日付オブジェクトをカレンダーに変換するには、四半期機能を参照してください。また興味があるかもしれません。あなたの予測のための日付のシーケンスを作成するseq.Date。 = "quarter"のオプションを使用して、3か月単位でシーケンスを作成します。 – Dave2e

答えて

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を次のように使用することを検討しています。 require(data.table) 必要(動物園) DT < -data.table(expand.grid(year = years.list、month = months.list)) DT < -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]