Reputation: 241
I need to run a statistical test and compute p_hat_6, using N = 10 samples each of size n = 10 from X ∼ uniform(0, 14). Here is my original loop to calculate p_hat at mu=6:
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
Using the same N and n, I need to repeat it 5 more times with the following changes:
(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)
How do I loop through as the intervals increase by 2 each time and mu increase by 1 each time?
Upvotes: 1
Views: 129
Reputation: 887048
We can create a function
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)
}
and use that in Map
Map(fun1, max_val = seq(14, 24, by = 2), mu_val = 6:11,
MoreArgs = list(N = 10, pvalue = pvalue, reject = reject))
-output
[[1]]
[1] 0
[[2]]
[1] 0.2
[[3]]
[1] 0.2
[[4]]
[1] 0
[[5]]
[1] 0.1
[[6]]
[1] 0.2
Or create an outer loop around the function
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
Upvotes: 1