我有
replicate(1000, t.test(rnorm(10)))
它的作用是从正态分布中抽取一个大小为 10 的样本,对其执行 at.test
并执行 1000 次。但是对于我的任务,我只对 p 值感兴趣(问题是:原假设被拒绝了多少次)。我如何只获得 p 值,或者我可以添加一些已经说明原假设被拒绝多少次的内容(p 值小于 0.05 的次数)
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)
这是我用来解决您的问题的步骤。请注意我是如何将其分解为最小的组件并逐步构建的:
#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