# What is the meaning of “lag” in Box.test (Ljung-Box test)

I want to conduct the Ljung-Box test on residuals of the ARIMA model with

Box.test(e, type = "Ljung-Box", fitdf = degrees_of_freedom)


where N = 3064, with 8 variables and additional 1 adjustmend from ar(1) in ARIMA model.

But I get weird results

Box-Ljung test

data: e
X-squared = 20.134, df = -3055, p-value = NA

Obviously df and p-value are off and I know it has to do something with the lag parameter in Box.test function. But I don't know what this parameter really does nor how to determine it.

Your problem is likely with fitdf, not lag. When applying the Ljung-Box test on residuals of an ARMA(p,q) model, fitdf should equal $$p+q$$. The first $$p+q$$ autocorrelations will be estimated at zero by construction, so you are supposed to adjust the asymptotic distribution of the test statistic under the null hypothesis for that. This is what fitdf does. In combination with lag, it facilitates setting the degrees of freedom parameter of the $$\chi^2$$ asymptotic distribution to lag-fitdf. What you apparently did instead is set fitdf to the length of the series minus your parameter count, which resulted in lag-fitdf being negative and thus producing nonsense null distribution and no $$p$$-value.
The degrees-of-freedom correction via fitdf would seem to make the test work alright, but apparently it does not, as explained in the thread "Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey". Thus you should not use the Ljung-Box test on residuals of an ARIMA model in the first place; use the Breusch-Godfrey test instead.