I'm trying to calculate sample covariance between these two vectors. I defined a function with two input variables. I don't know if it is correct? Also my formula for sample covariance won't run. Can anyone help me write it out in R?
xv = c(1., 5.5, 7.8, 4.2, -2.7, -5.4, 8.9)
yv = c(0.1, 1.5, 0.8, -4.2, 2.7, -9.4, -1.9)
sampleCov= function(x,y){
cov(xv,yv) = frac{sum_{i=1}^{n}(x_i-\mu_x)(y_i-\mu_y)}{n-1}].
return (Cov(xv,yv)
}
In other words, you can calculate the covariance between two stocks by taking the sum product of the difference between the daily returns of the stock and its average return across both the stocks.
In R programming, we make use of cov() function to calculate the covariance between two data frames or vectors. method – Any method to calculate the covariance such as Pearson, spearman. The default method is Pearson.
There is a base function in R called cov
that does exactly what you want, but if you want to write a function (no need to do that) you can try the following:
COV<- function(x,y) {
if(length(x)!=length(y)) {stop('x must have the same length as y ')}
x.bar <- mean(x)
y.bar <- mean(y)
N <- length(x)
Cov <- (sum((x-x.bar)*(y-y.bar))) / (N-1)
return(Cov)
}
COV(xv, yv)
[1] 8.697381
cov(xv, yv)
[1] 8.697381
As you can see COV
gives the same result as cov
so you don't have to write a function for that.
Besides, the body of your function doesn't have R syntax, instead you wrote LaTex syntax which are not the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With