2012-11-28 23 views
4

僅顯示多個t.tests

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

它能做什麼,它吸引十號從正態分佈的樣本,就可以進行t.test的p值,而做到這一點一千次。 但對於我的任務,我只對p值感興趣(問題是:零假設拒絕了多少次)。 我該如何獲得p值,或者我可以添加一些已經說明了原假設被拒絕的次數(p值小於0.05的次數)

回答

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) 
+0

非常感謝你的幫助,這是肯定的回答我需要的。 –

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 
+0

+1記住設置。種子 –

+0

哇,這是一個更好的答案。但我的老師永遠不會相信我自己想出了這個哈哈。我會堅持使用Brandon的方法並對數據進行排序,以便輕鬆計算出低於0.05的數據。 –

+0

您的意思是信貸到期時@mnel信貸的方法。 –