【问题标题】:Variable shows values but str shows NULL in r. How to check structure of such variable?变量显示值,但 str 在 r 中显示 NULL。如何检查此类变量的结构?
【发布时间】:2019-02-20 09:35:09
【问题描述】:
require(MTS)
rt=rnorm(200)
b<-archTest(rt, lag = 10)

此代码产生值

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

但是当使用typeof(b)str(b) 检查b 的结构时,它会给出NULL

这怎么可能?怎么知道b的结构,因为需要从这个变量中提取值。

【问题讨论】:

    标签: r null structure mts


    【解决方案1】:

    如果您查看archTest 的源代码,您的问题或多或少归结为这个:can I stop cat from returning NULL?答案是否定的。

    您可以修改archTest,但它会返回测试统计数据和 p 值(见下文)。 b 是一个命名向量。

    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
    

    我在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)
    }
    

    正如@42- 在 cmets 中指出的那样,return 调用是不必要的。

    【讨论】:

    • 小问题。不需要回电。
    猜你喜欢
    • 2015-09-23
    • 2013-07-17
    • 1970-01-01
    • 2019-03-15
    • 2017-11-11
    • 2013-04-13
    • 2013-07-24
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多