R语言 如何迭代计算t检验的p值

g2ieeal7  于 2023-09-27  发布在  其他
关注(0)|答案(4)|浏览(182)

a)从Χ 〜 Ν(μ Χ = 25,σ Χ = 4)生成50个值,并且从Υ 〜 Ν(μ Υ = 25,σ Υ = 4)生成50个值。使用t检验来检验平均值的相等性。
c)重复部分(a)2500次,并保留2500次测试中每一次的p值。每次重复应生成x的新样本和y的新样本。不要打印p值。请勿使用循环。
我在一个rnorm样本上求解了A部分,但我不知道从哪里开始获得2500个不同的x随机样本和2500个不同的y随机样本,以获得2500个不同的p值。
我也不知道如何确保我写的代码,使我的教授将得到相同的答案,我没有。我尝试设置种子,但这只能使它的p值都是相同的使用我的代码以上。

# Part A

set.seed(1081)
x = rnorm(50,25,4)
y = rnorm(50,25,4)

t.test(x,y)

#Part B
#The p-value is 0.3752.
#We do not reject the null hypothesis.

#Part C

x1 = sample(x, 2500, replace = T)
y1 = sample(y, 2500, replace = T)
pval = sample(t.test(x1,y1)$p.value, 2500, replace = T)
3okqufwl

3okqufwl1#

另一种方法是:

library(MASS)       #load MASS library

    s <- 4*diag(2500)   #create the variance matrix for the simulation
    set.seed(123)        # seed to replicate results

    x <- mvrnorm( 50, m= rep(25,times=2500), Sigma=s)  #draw 50 values, 25000 times 

    y <- mvrnorm( 50, m = rep(25, times=2500), Sigma=s) #draw 50 values, 2500 times

    diff <- x - y

    test <- apply(diff,2,t.test) #do the t.tests

    names(test) #some of the results you can print

如果你对代码有疑问,可以问我。

snz8szmq

snz8szmq2#

另一种可能性是使用replicate
请注意,您必须在函数外部设置随机种子。

myfun <- function(){
  x <- rnorm(50, 25, 4)
  y <- rnorm(50, 25, 4)

  return(t.test(x, y)$p.value)
}

set.seed(1)
p_vals <- replicate(2500, myfun())
vs91vp4v

vs91vp4v3#

您可以使用sapply()函数多次计算t检验的p值,而无需使用循环。
下面是一个示例:

set.seed(1081)
my.t.test <- function() {
  x <- rnorm(50, 25, 4)
  y <- rnorm(50, 25, 4)
  t.test(x, y)$p.value
}
p.values <- sapply(1:2500, function(i) my.t.test())
p.values

我们在这里使用sapply()来执行2500次t检验。我更喜欢数字向量,这就是为什么我使用sapply()。如果你喜欢将p值存储在列表中,你可以使用lapply()函数,它返回一个列表。你提到你的p值都是一样的。也许你是在函数内部设置种子?

qybjjes1

qybjjes14#

又一种可能性是:

set.seed(1081)
n <- 50
times <- 2500
x <- data.frame(matrix(rnorm(n*times, mean=25, sd=4), nrow=n))
y <- data.frame(matrix(rnorm(n*times, mean=25, sd=4), nrow=n))
pvals <- mapply(FUN = function(x,y) t.test(x,y)$p.value, x, y)
mean(pvals < .05)  # should be ~= .05

Loop simultaneously over two lists in R(jogo的评论)
但如果我们从字面上理解“每次重复都应该生成新样本”,@Cettt的答案可能就是我们想要的。

相关问题