# Covariance in R vs definition

a=rnorm(10)
b=rnorm(10)
x = cov(a,b)
y = mean((a-tail(am,1))*(b-tail(bm,1)))
z = mean(a*b)-mean(a)*mean(b)


According to https://en.wikipedia.org/wiki/Covariance covariance is defined as y or z but they do not match R covariance (x), why is that?

The difference is just because cov is sample covariance and the other formulas (assuming formula for y has been corrected) are population covariances.

According to help for cov:

The denominator n - 1 is used which gives an unbiased estimator of the (co)variance for i.i.d. observations.

If you are interested in population covariance, formulas should be:

n<- 10
a=rnorm(n)
b=rnorm(n)
x = (n-1)/n*cov(a,b)
y = mean((a-mean(a))*(b-mean(a)))
z = mean(a*b)-mean(a)*mean(b)


And if you are interested in sample covariance:

x = cov(a,b)
y = sum((a-mean(a))*(b-mean(a)))/(n-1)
z = sum(a*b)/(n-1)-n/(n-1)*mean(a)*mean(b)