2013-03-20 82 views
-1

我需要一些幫助做一個t檢驗。我知道如何做一個單一的數據集,但我需要幫助做2樣本t檢驗。我稱DATA1一個數據集:在R編程中做T.test

+3

請讓您的情況具有可重複性,即向我們提供模擬您的情況所需的數據和代碼。有關如何執行此操作的更多提示,請參閱http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example。 – 2013-03-20 11:51:50

+0

@PaulHiemstra你對複製/粘貼有何評論?我失去了鏈接到這個問題的次數! – 2013-03-20 11:52:33

+2

我在MacOS儀表板中將它作爲註釋。但是應該有一個Stack應用程序,允許您保存許多標準註釋。這可能會更好。 – 2013-03-20 11:58:06

回答

6

數據:

data1 <- data.frame(n = 15, mean = 14, sd = 8) 
data2 <- data.frame(n = c(17, 5, 8), mean = c(19, 17, 11), sd = c(7, 6, 9)) 

t檢驗功能(基於觀察,平均值和標準偏差的編號):

T.test <- function(n, mean, sd) { 
    s <- sum((n - 1) * sd^2)/(sum(n) - 2) # weighted variance 
    t <- sqrt(prod(n)/sum(n)) * (diff(mean)/sqrt(s)) # t statistic 
    df <- sum(n) - 2 # degrees of freedom 
    p <- (1 - pt(abs(t), df)) * 2 # p value 
    c(t = t, p = p) 
} 

應用函數的data2所有行:

apply(data2, 1, function(x) T.test(c(x[1], data1$n), 
            c(x[2], data1$mean), 
            c(x[3], data1$sd))) 

輸出顯示叔和p值用於LL行中data2

  [,1]  [,2]  [,3] 
t -1.98618371 -0.8215838 0.8730255 
p 0.05621594 0.4220631 0.3925227 
1

還有一個在R A內置函數

?t.test 

說明 執行對數據的矢量之一,兩樣本t檢驗。

#just an easy example 
a = c(12.9, 13.5, 12.8, 15.6, 17.2, 19.2, 12.6, 15.3, 14.4, 11.3) 
b = c(12.7, 13.6, 12.0, 15.2, 16.8, 20.0, 12.0, 15.9, 16.0, 11.1) 

t.test(a,b, paired=TRUE) 

Paired t-test 

data: a and b 
t = -0.2133, df = 9, p-value = 0.8358 
alternative hypothesis: true difference in means is not equal to 0 
95 percent confidence interval: 
-0.5802549 0.4802549 
sample estimates: 
mean of the differences 
-0.05 
+0

內置的't.test'函數需要原始數據,但OP有平均值,SD和n值。 – 2013-03-20 14:23:25

+0

@SvenHohenstein感謝您的精確度,我的錯誤 – 2013-03-20 14:32:10

+0

可悲的是,這不適用於我,因爲我比較具有不同n值的值 – 2013-03-21 23:14:37