1

我想将年份值和季度值转换为时间序列数据。

quaterly_data <- c(30.53,36.36,40.73,45.19,  

                   55.67,63.19,72.2,81.19,    

                   100.37,120.32,141.64,143.89,  

                   154.14,164.5,174.32,189.26,   

                   224.13,239.35,255.95,277.23)

#quarterly dates
library(zoo)
quarterly_dates <- as.yearqtr(seq(as.Date("2002/3/1"), as.Date("2006/12/1"), by = "3 months"))

日期如下所示:

[1] "2002 Q1" "2002 Q2" "2002 Q3" "2002 Q4" "2003 Q1" "2003 Q2" "2003 Q3" "2003 Q4" "2004 Q1" "2004 Q2"
[11] "2004 Q3" "2004 Q4" "2005 Q1" "2005 Q2" "2005 Q3" "2005 Q4" "2006 Q1" "2006 Q2" "2006 Q3" "2006 Q4"

我想编写一个函数来删除第一个元素“2002 Q1”,并将其放入myts <- ts( Quarterly_data,start = c(2002, 1), frequency = 4)。但我不知道该怎么做。

4

1 回答 1

1
x<-c("2002 Q1","2002 Q2" )
myyear<-substr(x,1,4)
> myyear
[1] "2002" "2002"
> myquarter<-substr(x,5,7)
> myquarter
[1] " Q1" " Q2"

如果你想申请全部,你可以使用ldplyplyr 包或do.call(rbind,)如下 使用do.call

myyear<-do.call(rbind,lapply(quarterly_dates,function(x)substr(x,1,4)))
myquarter<-do.call(rbind,lapply(quarterly_dates,function(x)substr(x,5,7)))
mydate<-cbind(myyear,myquarter)

Using plyr package:

library(plyr)
myyear<-ldply(lapply(quarterly_dates,function(x)substr(x,1,4)))
myquarter<-ldply(lapply(quarterly_dates,function(x)substr(x,5,7)))
mydate<-cbind(myyear,myquarter)
#rename the col names as year and quarter
names(mydate)<-c("year","quarter")
#make my year and my quarter as numeric
mydate$year<-as.numeric(mydate$year)
mydate$quarter<-as.numeric(mydate$quarter)

您可以使用包中的recode函数car将四分之一的十进制转换为数字:

library(car)
mydate$quarter<-recode(mydate$quarter,"0.25=1;0.5=2;0.75=3;else= 4")

> mydate
   year quarter
1  2002       4
2  2002       1
3  2002       2
4  2002       3
5  2003       4
6  2003       1
7  2003       2
8  2003       3
9  2004       4
10 2004       1
11 2004       2
12 2004       3
13 2005       4
14 2005       1
15 2005       2
16 2005       3
17 2006       4
18 2006       1
19 2006       2
20 2006       3
于 2013-08-12T16:13:15.300 回答