# Not sure I understand how R calculates the covariance

Please forgive this silly question, I'm fairly new to statistics.

Consider this R code:

    a = c(1,2,3,4,3,2,3,4,5,5,6,5,4,3,4,5,6,7,8,7,6,6,5,6,7,10,9)
b = c(10,9,7,6,5,6,7,8,4,6,6,5,4,5,6,5,4,5,6,7,5,4,4,5,4,3,2)
mean((a - mean(a))*(b-mean(b)))
[1] -2.42524
cov(a,b)
[1] -2.518519


why are these two values different? Are the mean and expected values not the same thing?

-

The difference is that the sample covariance function divides by $n-1$ while you are effectively dividing by $n$ when using the mean function. Try typing the following instead:
sum((a - mean(a))*(b - mean(b)))/(length(a) - 1)
The reason we divide by $n-1$ is so that the statistical property of unbiasedness will hold. That is, on average, we will not be over or underestimating the true underlying covariance.
NVM - I see what you did. All you need to do is put   around your code. –  Samuel Benidt Apr 19 at 0:45
Samuel - usually  ...  is used when writing 'inline code' - inserting code in the middle of a sentence. If you want to put a chunk of code in, after you paste it in, you highlight it and then click the $\{\}$ button at the top of the edit window, which indents 4 spaces, to get the whole codeblock formatted as code. –  Glen_b Apr 19 at 1:57