title: Using AOV on a dataframe to calculate variance among sample means - results don't match
body: <p>I am practising analysis of variance in R by building a manual function for calculating F-statistic and comparing results with aov() function. But for some reason my answers are not matching. Please could you help me identify where I have gone wrong. </p>
  
  <p>Here is  the data frame and code for using R's inbuilt function</p>
  
  <pre><code>s &lt;- c(245,258,239,241,277,276,263,274,215,232,225, 247,226,241,253,237,246,240)
  mydata &lt;- data.frame(cbind(s, ind = c(rep(1, 4), rep(2, 4), rep(3, 5), rep(4, 5))))
  summary(aov(mydata$s ~ mydata$ind))
  </code></pre>
  
  <p>Here is the summary of the result:</p>
  
  <pre><code>      Df Sum Sq Mean Sq F value Pr(&gt;F)
  mydata$ind   1    586   586.2   1.973  0.179
  Residuals   16   4754   297.1               
  </code></pre>
  
  <p>And here is my manual formula:</p>
  
  <pre><code>#building the 4 groups
  s1 &lt;- mydata$s[1:4]
  s2 &lt;- mydata$s[5:8]
  s3 &lt;- mydata$s[9:13]
  s4 &lt;- mydata$s[14:18]
  
  n1 &lt;- length(s1)
  n2 &lt;- length(s2)
  n3 &lt;- length(s3)
  n4 &lt;- length(s4)
  n &lt;- c(n1,n2,n3,n4)
  var &lt;- c(var(s1), var(s2), var(s3), var(s4))
  m1 &lt;- mean(s1)
  m2 &lt;- mean(s2)
  m3 &lt;- mean(s3)
  m4 &lt;- mean(s4)
  m &lt;- c(m1,m2,m3,m4)
  globalmean &lt;- sum(m*n)/sum(n)
  var.b &lt;- sum(n*(m-globalmean)^2)/(length(n)-1) #numerator of F-statistic i.e. variance between groups with degree of freed = n-1
  var.w &lt;- sum(var*(n-1))/sum(n-1) #denominator of F-statistic i.e. variance within groups with degree of freedom = total pop - no. of groups
  fstat &lt;- var.b/var.w #fstatistic
  </code></pre>
  
  <p>my fstat is coming out to be 18.96 while according aov() it should be 1.973. The funny thing is that the book that I am referring to says that my manually calculated value is the correct one. </p>
  
  <p>Where am I going wrong?</p>