Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
    [1] -2.518519

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

share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer
@Nick Stauner - thanks for editting my post. Could you tell me how to make the R code look nice like you did? – Samuel Benidt Apr 19 '14 at 0:42
NVM - I see what you did. All you need to do is put ` ` around your code. – Samuel Benidt Apr 19 '14 at 0:45
Thanks! I'll go off and read about the statistical property of unbiasedness. I hope there is some rigor to using it and not just convenience! – kamula Apr 19 '14 at 1:52
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 '14 at 1:57
@Glen_b Thanks - I will definitely make use of this feature in the future – Samuel Benidt Apr 19 '14 at 2:04

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.