Contradictory result from adf.test and ndiffs in R I want to check if a time series is stationary in R.
For ndiffs,
 > ndiffs(GDPlst_t$GDP110000, test="adf")
 [1] 0

the result is 0.
However for adf.test
> adf.test(GDPlst_t$GDP110000)

Augmented Dickey-Fuller Test

data:  GDPlst_t$GDP110000
Dickey-Fuller = -2.2519, Lag order = 3, p-value = 0.4729
alternative hypothesis: stationary

Why do they differ? And what is the detailed ADF test in ndiffs? How are the lag order and type of ADF (3 types) determined?
 A: We need to set lag order k=1 in adf.test to be able to compare with ndiffs.
For example, if ndiffs(x, test='adf') returns 2, it suggests 2 lagged differences are required for a stationary series, which means:

*

*adf.test(x, k=1) => not significant

*adf.test(diff(x), k=1) => not significant

*adf.test(diff(diff(x)), k=1) => Significant!
Using the example from @Richard Hardy's answer, a function based on adf.test is equivalent to ndiffs.
set.seed(1)
x_random = rnorm(1000) # a random stationary series
x = cumsum(cumsum(cumsum(x_random))) # order 3 integration

# Note that `diff` cancels out `cumsum`
# the following three are the same
x_random[-(1:3)][1:5]
diff(diff(diff(x)))[1:5]
diff(x,differences=3)[1:5]
# 1.5952808  0.3295078 -0.8204684  0.4874291  0.7383247

# using `ndiffs` for the min number of differences required for a stationary series 
library(forecast)
ndiffs(x, max.d=10, test="adf", type='trend')
# 0
ndiffs(diff(x,differences=1), max.d=10, test="adf", type='trend')
# 2
ndiffs(diff(x,differences=2), max.d=10, test="adf", type='trend')
# 1
ndiffs(diff(x,differences=3), max.d=10, test="adf", type='trend')
# 0

#an equivalent function based on `adf.test`
library(tseries)
ndiffs_adf.test <- function(x) {
    for (i in 0:10) {
        if (i==0){
            x_ = x
          } else {
            x_ = diff(x, differences=i)
          }
        if (adf.test(x_, k=1)$p.value < 0.05) return(i)
      }
    return(NULL)
  }
ndiffs_adf.test(x)
# 0
ndiffs_adf.test(diff(x,differences=1))
# 2
ndiffs_adf.test(diff(x,differences=2))
# 1
ndiffs_adf.test(diff(x,differences=3))
# 0

