title: Why is the var() function giving me a different answer than my calculated variance?
body: <p>I wasn't sure if this should go in SO or some other .SE, so I will delete if this is deemed to be off-topic.</p>
  
  <p>I have a vector and I'm trying to calculate the variance "by hand" (meaning based on the definition of variance but still performing the calculations in R) using the equation: <code>V[X] = E[X^2] - E[X]^2</code> where <code>E[X] = sum (x * f(x))</code> and <code>E[X^2] = sum (x^2 * f(x))</code></p>
  
  <p>However, my calculated variance is different from the <code>var()</code> function that R has (which I was using to check my work). Why is the <code>var()</code> function different? How is it calculating variance? I've checked my calculations several times so I'm fairly confident in the value I calculated. My code is provided below.</p>
  
  <pre><code>vec &lt;- c(3, 5, 4, 3, 6, 7, 3, 6, 4, 6, 3, 4, 1, 3, 4, 4)
  range(vec)
  counts &lt;- hist(vec + .01, breaks = 7)$counts
  fx &lt;- counts / (sum(counts)) #the pmf f(x)
  x &lt;- c(min(vec): max(vec)) #the values of x
  exp &lt;- sum(x * fx) ; exp #expected value of x
  exp.square &lt;- sum(x^2 * fx) #expected value of x^2
  var &lt;- exp.square - (exp)^2 ; var #calculated variance
  var(vec)
  </code></pre>
  
  <p>This gives me a calculated variance of 2.234 but the <code>var()</code> function says the variance is 2.383.</p>