時系列データを結合後、系列同士の処理

> data1<-read.table(file="gold.csv",header=TRUE,sep=",")

> data2<-read.table(file="dow.csv",header=TRUE,sep=",")

> head(data1)
        DATE  VALUE
1 1968-04-01 38.000
2 1968-04-02 37.600
3 1968-04-03 37.700
4 1968-04-04 36.700
5 1968-04-05 37.200
6 1968-04-08 37.000

> head(data2)
        DATE    VALUE
1 2004-08-30 10122.52
2 2004-08-31 10173.92
3 2004-09-01 10168.46
4 2004-09-02 10290.28
5 2004-09-03 10260.20
6 2004-09-06        .

> data1<-subset(data1,data1[,2]!=".")

> data2<-subset(data2,data2[,2]!=".")

> head(data1)
        DATE  VALUE
1 1968-04-01 38.000
2 1968-04-02 37.600
3 1968-04-03 37.700
4 1968-04-04 36.700
5 1968-04-05 37.200
6 1968-04-08 37.000

> head(data2)
        DATE    VALUE
1 2004-08-30 10122.52
2 2004-08-31 10173.92
3 2004-09-01 10168.46
4 2004-09-02 10290.28
5 2004-09-03 10260.20
7 2004-09-07 10342.79

> data3<-merge(data1,data2,by="DATE",sort=F)

> head(data3)
        DATE VALUE.x  VALUE.y
1 2004-08-31 408.100 10173.92
2 2004-09-01 408.000 10168.46
3 2004-09-02 407.800 10290.28
4 2004-09-03 405.800 10260.20
5 2004-09-07 401.800 10342.79
6 2004-09-08 398.100 10313.36

> colnames(data3)[2]<-"gold"

> colnames(data3)[3]<-"dow"

> head(data3)
        DATE    gold      dow
1 2004-08-31 408.100 10173.92
2 2004-09-01 408.000 10168.46
3 2004-09-02 407.800 10290.28
4 2004-09-03 405.800 10260.20
5 2004-09-07 401.800 10342.79
6 2004-09-08 398.100 10313.36

> data3[,1]<-as.Date(data3[,1])

> data3[,2]<-as.double(as.character(data3[,2]))

> data3[,3]<-as.double(as.character(data3[,3]))

> head(data3)
        DATE  gold      dow
1 2004-08-31 408.1 10173.92
2 2004-09-01 408.0 10168.46
3 2004-09-02 407.8 10290.28
4 2004-09-03 405.8 10260.20
5 2004-09-07 401.8 10342.79
6 2004-09-08 398.1 10313.36

> data4<-cbind(data3,data.frame(ratio=data3[,3]/data3[,2]))

> head(data4)
        DATE  gold      dow    ratio
1 2004-08-31 408.1 10173.92 24.92997
2 2004-09-01 408.0 10168.46 24.92270
3 2004-09-02 407.8 10290.28 25.23364
4 2004-09-03 405.8 10260.20 25.28388
5 2004-09-07 401.8 10342.79 25.74114
6 2004-09-08 398.1 10313.36 25.90646

> par(mfrow=c(3,1))

> plot(data4[,1],data4[,2],xlab="date",ylab="gold",type="l")

> plot(data4[,1],data4[,3],xlab="date",ylab="dow",type="l")

> plot(data4[,1],data4[,4],xlab="date",ylab="dowgold ratio",type="l")
> 

20140902_02 参考文献 ・石田基広.『改訂2版 R言語逆引きハンドブック』.C&R研究所.pp703アプリケーション R Core Team (2013). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL http://www.R-project.org/.