2016-11-18 163 views
2

在R中,函数ar.yw如何估计方差?具体来说,数字“var.pred”来自哪里?它似乎不是来自通常的YW估计的方差,也不是平方残差的总和除以df(即使对于df应该是什么意见不一致,没有一个选项给出了等同于var.pred的答案) 。是的,我知道有比YW更好的方法;试图弄清楚R在做什么。ar.yw如何估计方差

set.seed(82346) 
temp <- arima.sim(n=10, list(ar = 0.5), sd=1) 
fit <- ar(temp, method = "yule-walker", demean = FALSE, aic=FALSE, order.max=1) 

## R's estimate of the sigma squared 
fit$var.pred 
## YW estimate 
sum(temp^2)/10 - fit$ar*sum(temp[2:10]*temp[1:9])/10 
## YW if there was a mean 
sum((temp-mean(temp))^2)/10 - fit$ar*sum((temp[2:10]-mean(temp))*(temp[1:9]-mean(temp)))/10 
## estimate based on residuals, different possible df. 
sum(na.omit(fit$resid^2))/10 
sum(na.omit(fit$resid^2))/9 
sum(na.omit(fit$resid^2))/8 
sum(na.omit(fit$resid^2))/7 
+0

A guess ...这是预测包中的函数吗?你知道R包都是开源的吗? –

+0

@ 42,不,这是“stats”包的一部分,即给我们“lm”和所有其他基本统计功能的相同包。因此,人们可能会认为,即使它是开源的,它会做一些合理的事情。 – chucky

回答

1

如果没有记录,需要阅读代码。

?ar.yw 

其中说:“在ar.yw创新的方差矩阵是从拟合系数和x的自协方差计算出来的。如果这还不够的解释,那么你需要看一下代码:

methods(ar.yw) 
#[1] ar.yw.default* ar.yw.mts*  
#see '?methods' for accessing help and source code 

getAnywhere(ar.yw.default) 
# there are two cases that I see 
x <- as.matrix(x) 
nser <- ncol(x) 
if (nser > 1L) # .... not your situation 
#.... 
else{ 
    r <- as.double(drop(xacf)) 
    z <- .Fortran(C_eureka, as.integer(order.max), r, r, 
     coefs = double(order.max^2), vars = double(order.max), 
     double(order.max)) 
    coefs <- matrix(z$coefs, order.max, order.max) 
    partialacf <- array(diag(coefs), dim = c(order.max, 1L, 
     1L)) 
    var.pred <- c(r[1L], z$vars) 
    #....... 
    order <- if (aic) 
     (0L:order.max)[xaic == 0L] 
    else order.max 
    ar <- if (order) 
     coefs[order, seq_len(order)] 
    else numeric() 
    var.pred <- var.pred[order + 1L] 
    var.pred <- var.pred * n.used/(n.used - (order + 1L)) 

所以你现在需要找到Fortran代码为C_eureka。我想我在这里找到它:https://svn.r-project.org/R/trunk/src/library/stats/src/eureka.f这是我认为返回var.pred估计值的代码。我不是一个时间系列的人,你有责任回顾这个过程,以适应你的问题。

 subroutine eureka (lr,r,g,f,var,a) 
c 
c  solves Toeplitz matrix equation toep(r)f=g(1+.) 
c  by Levinson's algorithm 
c  a is a workspace of size lr, the number 
c  of equations 
c 
    snipped 
c estimate the innovations variance 
     var(l) = var(l-1) * (1 - f(l,l)*f(l,l)) 
     if (l .eq. lr) return 
     d = 0.0d0 
     q = 0.0d0 
     do 50 i = 1, l 
      k = l-i+2 
      d = d + a(i)*r(k) 
      q = q + f(l,i)*r(k) 
    50  continue