Reputation: 1
I was confused by covariance in R. When I use E(x*y)-E(x)E(y), it returns a different value for cov(). Can you help me to understand it? my code:
spot<- c(0.5,0.61,-0.22,-0.35,0.79,0.04,0.15,0.7,-0.51,-0.41)
future<- c(0.56,0.63,-0.12,-0.44,0.6,-0.06,0.01,0.8,-0.56,-0.46)
ms<-mean(spot)
mf<-mean(future)
msf<-mean(spot*future)
cov<- msf-mf*ms
#the way above is wrong for giving 0.22272 while cov gives 0.2474667
covr<- cov(spot,future)
Upvotes: 0
Views: 51
Reputation: 3116
I don't think you used the correct formula. The formula for covariance between two vectors X
and Y
each of length n
is:
cov(X,Y) = sigma((X-mean(X))*(Y-mean(Y)))/(n-1)
spot<- c(0.5,0.61,-0.22,-0.35,0.79,0.04,0.15,0.7,-0.51,-0.41)
future<- c(0.56,0.63,-0.12,-0.44,0.6,-0.06,0.01,0.8,-0.56,-0.46)
covar = sum((spot-mean(spot))*(future-mean(future)))/(length(spot)-1)
#covar
#0.2474667
Upvotes: 1