仅显示多个t.tests的p值

时间:2012-11-28 23:50:14

标签: r sample

我有

replicate(1000, t.test(rnorm(10)))

它从正态分布中抽取大小为10的样本,对其执行t.test,并执行1000次。 但对于我的任务,我只对p值感兴趣(问题是:零假设被拒绝了多少次)。 我如何只得到p值,或者我可以添加一些已经说明零假设被拒绝多少次的东西(p值小于0.05的次数)

2 个答案:

答案 0 :(得分:6)

t.test返回类htest的对象,该对象是包含许多组件的列表,包括p.value(这是您想要的)。

你有几个选择。

您可以将t.test结果保存在列表中,然后提取p.value组件

# simplify = FALSE to avoid coercion to array
ttestlist <- replicate(1000, t.test(rnorm(10)), simplify = FALSE)
ttest.pval <- sapply(ttestlist, '[[', 'p.value')

或者您只能保存t.test对象

的组件
pvals <- replicate(1000, t.test(rnorm(10))$p.value)

答案 1 :(得分:5)

以下是我用来解决问题的步骤。注意我如何将其分解为最小的组成部分并逐步构建它:

#Let's look at the structure of one t.test to see where the p-value is stored
str(t.test(rnorm(10)))
#It is named "p.value, so let's see if we can extract it
t.test(rnorm(10))[["p.value"]]
#Now let's test if its less than your 0.05 value
ifelse(t.test(rnorm(10))[["p.value"]]< 0.05,1,0)
#That worked. Now let's replace the code above in your replicate function:
replicate(1000, ifelse(t.test(rnorm(10))[["p.value"]]< 0.05,1,0))
#That worked too, now we can just take the sum of that:
#Make it reproducible this time
set.seed(42)
sum(replicate(1000, ifelse(t.test(rnorm(10))[["p.value"]]< 0.05,1,0)))

应该产生这个:

[1] 54