2015-04-30 26 views
0

如何爲依賴樣本寫入R函數t檢驗?沒有使用現有的函數(如t.test())?相關樣本t檢驗的R函數?

ttest <- function(x,y) { 
n1<- length(y)  #y length 
n2<- length(x)  #x length 
somay <- sum(y) 
somax <- sum(x) 
y1 <- (somay)/n1  #y mean 
y2<- (somax)/n2  #x mean 
dadosy <- na.omit(y) 
dadosx <- na.omit(x) 
disvquad1 <- (dadosy-y1)^2 
disvquad2 <- (dadosx-y2)^2 
s12<- (1/(n1-1))*sum(disvquad1) #variance of y 
s22<- (1/(n2-1))*sum(disvquad2) #variance of x 
s2 <- ((n1-1)*s12+(n2-1)*s22)/((n1-1)+(n2-1)) 
s<- (s2)^(1/2) 
t<- (y1-y2)/(sqrt(1/n1+1/n2)*s)  #test statistic 
return(t) 
} 

ttest(x,y) 

這是依賴樣本t檢驗的正確解決方案。

+1

我不確定你到底在問什麼。你問你是否使用正確的公式?如果是這樣,那真的是一個關於統計的問題,屬於[stats.se]。似乎很奇怪,以避免在使用R時使用標準R函數。如果這實際上是一個編碼問題,則應該包含您正在嘗試實現的公式。 – MrFlick

回答

0

根據this tutorial,成對t檢驗不過是測試兩個向量的差異(或偏差)。

下面是一個快速試用。它開始選擇兩個向量之間的完整情況(complete.cases())。然後意味着,獲得標準偏差和標準誤差。最後計算t-靜態值和p-值 - 注意默認情況下平均差值爲0(mu = 0),並假定備選假設是雙側的。

ttest <- function(x, y, mu = 0, ...) { 
    # keep only non-NULL 
    complete <- complete.cases(x, y) 
    x <- x[complete] 
    y <- y[complete] 
    # build statistic 
    d <- y - x 
    d.mu <- mean(d) 
    d.se <- sd(d)/sqrt(length(x)) # standard error 
    t <- (d.mu - mu)/d.se 
    # returns t statistic and p value, assumes two sided 
    c(t_value = t, p_value = pt(t, df = length(x)-1)) 
} 

set.seed(1237) 
ttest(rnorm(10),rnorm(10)) 
# t_value p_value 
# 0.9163995 0.8083221