创建循环 运行 统计测试

Creating a loop to run a statistical test

我需要 运行 统计测试并计算 p_hat_6,使用来自 X ∼ uniform(0, 14) 的 N = 10 个样本,每个样本大小为 n = 10。这是我在 mu=6:

处计算 p_hat 的原始循环
pvalue <- rep(0,10)
reject <- 0
alpha <- 0.05
N <- 10

for (n in seq_along(pvalue)){
  pvalue[n] <- wilcox.test(runif(10,0,14), mu=6)$p.value
  reject[n] <- ifelse(pvalue[n] > alpha,0,1)
}

p_hat_6 <- (sum(reject))/N
p_hat_6

使用相同的 N 和 n,我需要再重复 5 次,并进行以下更改:

(1) Data from X ∼ uniform(0, 16) and compute p_hat_7 (mu=7)
(2) Data from X ∼ uniform(0, 18) and compute p_hat_8 (mu=8)
(3) Data from X ∼ uniform(0, 20) and compute p_hat_9 (mu=9)
(4) Data from X ∼ uniform(0, 22) and compute p_hat_10 (mu=10)
(5) Data from X ∼ uniform(0, 24) and compute p_hat_11 (mu=11)

interval每次加2,mu每次加1,如何循环?

我们可以创建一个函数


fun1 <- function(N, pvalue, reject, max_val, mu_val) {
  for (n in seq_along(pvalue)){
    pvalue[n] <- wilcox.test(runif(N ,0, max_val), mu=mu_val)$p.value
     reject[n] <- ifelse(pvalue[n] > alpha,0,1)
     }

   p_hat_6 <- (sum(reject))/N
   return(p_hat_6)
   }

并在 Map

中使用它
Map(fun1, max_val = seq(14, 24, by = 2), mu_val = 6:11,
       MoreArgs = list(N = 10, pvalue = pvalue, reject = reject))   

-输出

[[1]]
[1] 0

[[2]]
[1] 0.2

[[3]]
[1] 0.2

[[4]]
[1] 0

[[5]]
[1] 0.1

[[6]]
[1] 0.2

或者围绕函数创建一个外循环

mu_val <- 6:11
max_val <- seq(14, 24, by = 2)
out <- numeric(length(mu_val))
for(i in seq_along(mu_val)) {
    out[i] <- fun1(N = 10, pvalue = pvalue, 
      reject = reject, max_val = max_val[i], mu_val = mu_val[i])
}

out
[1] 0.1 0.1 0.1 0.1 0.3 0.0

数据

N <- 10
pvalue <- rep(0, N)
reject <- rep(0, N)
alpha <- 0.05