Search code examples
rnullstructuremts

Variable shows values but str shows NULL in r. How to check structure of such variable?


require(MTS)
rt=rnorm(200)
b<-archTest(rt, lag = 10)

This code results in the values

Q(m) of squared series(LM test):  
Test statistic:  7.694531  p-value:  0.6586466 
Rank-based Test:  
Test statistic:  20.80503  p-value:  0.02249487

But when the structure of b is checked using typeof(b) and str(b), it gives NULL.

How is it possible? How can one knows the structure of b as it is needed to extract values from this variable.


Solution

  • If you look at the source code of archTest, you're question boils down to more or less this one: can I stop cat from returning NULL? To which the answer is no.

    You can modify archTest however such that it returns the test statistic and p-value (see below). b is a named vector.

    b <- my_archTest(rt, lag = 10)
    str(b)
    # Named num [1:2] 7.565 0.671
    # - attr(*, "names")= chr [1:2] "Test statistic" "p-value"
    b
    #Test statistic        p-value 
    #     7.5653283      0.6712114
    b["Test statistic"]
    #Test statistic 
    #      7.565328
    

    I added three lines at the end of MTS::archTest.

    my_archTest <- function (rt, lag = 10) {
      at = rt
      if (is.matrix(at)) 
        at = at[, 1]
      m1 = acf(at^2, lag.max = lag, plot = F)
      acf = m1$acf[2:(lag + 1)]
      nT = length(at)
      c1 = c(1:lag)
      deno = rep(nT, lag) - c1
      Q = sum(acf^2/deno) * nT * (nT + 2)
      pv1 = 1 - pchisq(Q, lag)
      cat("Q(m) of squared series(LM test): ", "\n")
      cat("Test statistic: ", Q, " p-value: ", pv1, "\n")
      rk = rank(at^2)
      m2 = acf(rk, lag.max = lag, plot = F)
      acf = m2$acf[2:(lag + 1)]
      mu = -(rep(nT, lag) - c(1:lag))/(nT * (nT - 1))
      v1 = rep(5 * nT^4, lag) - (5 * c(1:lag) + 9) * nT^3 + 9 * 
        (c(1:lag) - 2) * nT^2 + 2 * c(1:lag) * (5 * c(1:lag) + 
                                                  8) * nT + 16 * c(1:lag)^2
      v1 = v1/(5 * (nT - 1)^2 * nT^2 * (nT + 1))
      QR = sum((acf - mu)^2/v1)
      pv2 = 1 - pchisq(QR, lag)
      cat("Rank-based Test: ", "\n")
      cat("Test statistic: ", QR, " p-value: ", pv2, "\n")
    
      out <- c("Test statistic" = QR, # new lines added here
               "p-value" = pv2)
      return(out)
    
    # or instead simply
    # c("Test statistic" = QR,
    #   "p-value" = pv2)
    }
    

    As pointed out by @42- in the comments, the return call is not necessary.