1

下面的摘录来自“假设的置换、参数和引导测试”,第三版。菲利普·古德(第 58-61 页),第 3.7.2 节。

我试图在 R 中实现这个排列测试(见下文)来比较两个方差。我现在正在考虑如何计算 p 值,以及测试是否允许不同的替代假设(更大、更少、两侧),我不确定如何进行。

您能否对此有所了解,并可能对代码提出一些批评?非常感谢!

在此处输入图像描述

# Aly's non-parametric, permutation test of equality of variances
# From "Permutation, Parametric and Bootstrap Tests of Hypotheses", Third Ed. 
# by Phillip Good (pages 58-61), section 3.7.2.

# Implementation of delta statistic as defined by formula in page 60
# x_{i}, order statistics
# z = x_{i+1} - x_{i}, differences between successive order statistics
aly_delta_statistic <- function(z) {
  z_length <- length(z)
  m <- z_length + 1
  i <- 1:z_length
  sum(i*(m-i)*z)
}

aly_test_statistic <- function(sample1, sample2 = NULL, nperm = 1) {

  # compute statistic based on one sample only: sample1
  if(is.null(sample2)) {
    sample1 <- sort(sample1)
    z <- diff(sample1)
    return(aly_delta_statistic(z))
  }

  # statistic based on randomization of the two samples
  else {
    m1 <- length(sample1)
    m2 <- length(sample2)
    # allocate a vector to save the statistic delta
    statistic <- vector(mode = "numeric", length = nperm)
    for(j in 1:nperm) {
      # 1st stage resampling (performed only if samples sizes are different)
      # larger sample is resized to the size of the smaller
      if(m2 > m1) {
         sample2 <- sort(sample(sample2, m1))
         m <- m1
      } else {
         sample1 <- sort(sample(sample1, m2))
         m <- m2
      }
      # z-values: z1 in column 1 and z2 in column 2.
      z_two_samples <- matrix(c(diff(sample1), diff(sample2)), ncol = 2)
      # 2nd stage resampling
      z <- apply(z_two_samples, 1, sample, 1)
      statistic[j] <- aly_delta_statistic(z)
    }
    return(statistic)
  }
}
4

0 回答 0