1.獨立樣本的t檢驗
t.test調用格式1:其中是一個數值型變量,x爲二分變量
t.test(y~x, data)
t.test調用格式2:其中有y1,y2爲數值型變量。
t.test(y1,y2)
例子:比較美國南方與非南方地區犯罪的監禁概率是否相同。
library(MASS)
t.test(Prob ~ So,data=UScrime)
輸出:
Welch Two Sample t-test
data: Prob by So
t = -3.8954, df = 24.925, p-value = 0.0006506
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-0.03852569 -0.01187439
sample estimates:
mean in group 0 mean in group 1
0.03851265 0.06371269
因此,可以拒絕南方與非南方各州犯罪具有相同監禁概率的假設。
2.非獨立樣本的t檢驗
如,年長的男性與年輕的男性失業率概率是否相同,此時,年齡與失業率是有關的,所以是非獨立的。
非獨立樣本的t檢驗假定組間差異呈正態分佈。
調用格式:其中y1,y2爲非獨立的數值向量
t.test(y1,y2,paired=TRUE)
library(MASS)
with(UScrime, t.test(U1,U2,paired=TRUE))
輸出:Paired t-test
data: U1 and U2
t = 32.407, df = 46, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
57.67003 65.30870
sample estimates:
mean of the differences
61.48936
因此,可以拒絕不同年齡男性失業率相同的原假設。
3.卡方獨立性檢驗
卡方檢驗可以使用chisq.test()函數對二維表的行變量或者列變量進行檢驗。
library(vcd)
mytable<-xtabs(~Treatment+Improved, data=Arthritis)
mytable
chisq.test(mytable)
輸出:
Pearson's Chi-squared test
data: mytable
X-squared = 13.055, df = 2, p-value = 0.001463
因此,治療與改善效果並不獨立。
##############################################################
以下爲在真實病例中的應用,檢驗兩種不同的疾病與年齡,性別以及發病部位有無顯著差異。
library(vcd)
library(xlsx)
data<-read.xlsx("DiseaseData.xlsx",sheetIndex = 1)
head(data)
性別以及發病部位與兩種病的關係用卡方獨立檢驗:
a<-xtabs(~class+sex,data)
b<-xtabs(~class+part,data)
chisq.test(a)
chisq.test(b)
比較年齡(單位:月)與兩種病是否有相關性,用t檢驗
t.test(age~class,data)