1.单样本t检验(正态总体)
a = c(20.99,20.41,20.10,20.00,20.91,22.60,20.99,20.42,20.90,22.99,23.12,20.89)
qqnorm(scale(a)) # 正态性检验
t.test(a,mu = 20.7,alternative = "two.sided",conf.level = 0.95)
u0 = 72
u1 = 74.2
s = 6.5
n = 25
t = (u0-u1)/(s/sqrt(n))
v = n-1
p = 2*pt(-abs(t),v) # p = 2*f(-inf<t<-abs(t)),f()为自由度为v的概率密度函数
2.配对设计资料的t检验(和单样本t检验本质一样)
y1 = c(2.41,2.90,2.75,2.23,3.67,4.49,5.16,5.45,2.06,1.64,1.06,0.77)
y2 = c(2.80,3.04,1.88,3.43,3.81,4,4.44,5.41,1.24,1.83,1.45,0.92)
qqnorm(scale(y1-y2)) # 正态性检验
t.test(y1,y2,,paired = T,alternative = "two.sided",conf.level = 0.95)
library(ggplot2)
library(ggpubr)
data = data.frame(group = c(rep('A',12),rep('B',12)),
value = c(2.41,2.90,2.75,2.23,3.67,4.49,5.16,5.45,2.06,1.64,1.06,0.77,
2.80,3.04,1.88,3.43,3.81,4,4.44,5.41,1.24,1.83,1.45,0.92)
)
p <- ggpaired(data, x = "group", y = "value",
color = "group",
palette = "jco", # 自动使用医学杂志配色
line.color = "gray", line.size = 0.4,
xlab = 'group',
ylab = 'value')
p + stat_compare_means(label = "p.signif", #显著性表示方式:'p.signif'、'p.format'
method = 't.test',
paired = TRUE, #配对t检验
label.y = 6,label.x = 1.5) # p值在X、Y轴上的位置
3.独立样本t检验
attach(mtcars)
wt1 = mtcars[vs ==0,]$wt
wt2 = mtcars[vs ==1,]$wt
var.test(wt1,wt2,ratio = 1) # 方差齐次性检验
qqnorm(scale(mtcars$wt)) # 正态性检验
t.test(wt~vs,var.equal = T) # 同方差
detach(mtcars)
data = mtcars[,c('wt','vs')]
p = ggboxplot(data, x = 'vs', y = 'wt',
fill = 'vs',
palette = 'jco',
width = 0.3,
add = 'jitter',
bxp.errorbar = T,
bxp.errorbar.width = 0.3)
p + geom_signif(xmin = '0',
xmax = '1',
y_position = 6,
annotations = '***')