Calculating BIC manually for lm object
<p>I can't quite figure out why I'm having trouble calculating the Bayesian Information Criterion correctly, and was hoping someone could point me in the right direction. </p>

<p>I am doing this because I am trying to calculate the BIC manually (for <code>plm</code> objects, which don't seem to have an established routine associated with them). I took the formula from the <a href="https://en.wikipedia.org/wiki/Bayesian_information_criterion" rel="noreferrer">Wikipedia page</a>, which gives the formula for the BIC in terms of the Residual Sum of Squares, rather than the Log Likelihood. </p>

<pre><code>y&lt;-rnorm(100)
x&lt;-rnorm(100)
m.test&lt;-lm(y ~ x) 

n&lt;-100 
rss&lt;-sum(m.test$residuals^2) 
k&lt;-3 
bic.mine&lt;-n*log(rss/n)+k*log(n) #formula from wikipedia
bic.stats&lt;-BIC(m.test) #using stats package
abs(bic.mine-bic.stats) #mine is off!
</code></pre>

<p>Running the code a bunch of times, I realize that the difference between the BIC I obtain and the BIC obtained from the stats package is constant, so my suspicion is that I'm missing some kind of scaling factor. Is that right? Thanks in advance.</p>

<p><strong>Edit</strong>: Thanks for all the comments. I tried to implement the suggestions and post an answer, but I'm still off by a constant. Revised code below. </p>

<pre><code>y&lt;-rnorm(100)
x&lt;-rnorm(100)
m.test&lt;-lm(y ~ x) 

n&lt;-100
res&lt;-m.test$residuals
rss&lt;-sum(res^2) 
k&lt;-3; df&lt;-n-k; w&lt;-rep(1,N) #params, dfs, weights
ll&lt;-0.5 * (sum(log(w)) - n *
             (log(2 * pi) + 1 - log(n) + log(sum(w * res^2))))
ll.stats&lt;-logLik(m.test)
abs(ll.stats-ll)==0 #same, prob is not here

bic.mine&lt;-n*log(rss/n)+k*log(n) #formula from wikipedia
bic.exact&lt;- -2 * ll + log(n) * df #suggestions from comments
bic.stats&lt;-BIC(m.test) #using stats package
abs(bic.mine-bic.stats) #mine was off
abs(bic.exact-bic.stats) #this is still off, though
</code></pre>