Linear Regression, Formula to Calculate AIC based on Residual Sum of Squares + Number of Predictors

In linear regression, suppose I have Residual Sum of Squares, how to calculate AIC from it?

set.seed(2019)
x = rnorm(1000,5,1)
e = rnorm(1000)
y = x * 2+e
m0 = lm(y~x)
AIC(m0) # 2873.427


How to calculate AIC = 2873.427 given there's 1 predictor, there's 1000 observations and the RSS is 1029.991?

Code:

res <- m0$$residuals p <- m0$$rank
N <- length(res)
w <- rep.int(1, N)
loglike.calc = .5* (sum(log(w)) - N * (log(2 * pi) + 1 - log(N) +log(sum(w*res^2))))
aic.calc = -2*as.numeric(loglike.calc)+2*(length(m0\$coefficients)+1)


And then you get

> aic.calc
[1] 2873.427

• If your answer is purely "how to do this in code" it's probably off topic. If your intent is to convey and explain the underlying formula, this would require more than just a line of code – Glen_b Mar 6 '19 at 5:35