# 2014-03-31 # # example of covariance matrix # # clear memory rm(list=ls()) # reset the plot window to full sized plot par(mfrow=c(1,1)) source("scripts/loadano2.R") month<-"Jan" # Station 1 x1<-loadano2(station="USW00014750",state="NY",month=month,start=1950,end=2012) # Station 2 x2<-loadano2(station="USW00094728",state="NY",month=month,start=1950,end=2012) xm1<-mean(x1$ano) xm2<-mean(x2$ano) x1$ano<-x1$ano-xm1 x2$ano<-x2$ano-xm2 # forming a matrix from existing vectors of same dimension # (length(x1$ano)==length(x2$ano)) X<-cbind(x1$ano,x2$ano) N<-length(x1$ano) # R for the advanced: special string creation from a vector res<-paste(dim(X),collapse=' x ') print(paste("dimension of the matrix X: (",res,")",sep='')) # matrix multiplication in R %*% # transpose of a matrix t() Sxx<-t(X)%*%X res<-paste(dim(Sxx),collapse=' x ') print(paste("dimension of the matrix Sxx: (",res,")",sep='')) Cxx<-1/(N-1)*Sxx print(Cxx) plot(x1$ano,x2$ano) # fitted regression line is now # (centered data => intercept = 0) bfit<-cor(x1$ano,x2$ano)*sd(x2$ano)/sd(x2$ano) lines(x1$ano,bfit*x1$ano,col=5)