展开

Z检验

最后发布时间 : 2022-11-09 22:56:57 浏览量 :

单尾检验和双尾检验

library(BSDA)

# 问题: 比较两个城市 人的IQ是否相等
cityA = c(82, 84, 85, 89, 91, 91, 92, 94, 99, 99,
         105, 109, 109, 109, 110, 112, 112, 113, 114, 114)

cityB = c(90, 91, 91, 91, 95, 95, 99, 99, 108, 109,
         109, 114, 115, 116, 117, 117, 128, 129, 130, 133)

# 执行两样本的Z检验
z.test(x=cityA, y=cityB, mu=0, sigma.x=15, sigma.y=15) # Z 统计量为 -1.7182
z.test(x=cityB, y=cityA, mu=0, sigma.x=15, sigma.y=15 )# Z 统计量为 -1.7182

# 计算p值, 由于是双尾检验,所有乘以2
pnorm(-1.7182,mean=0,sd=1)*2
(1-pnorm(1.7182,mean=0,sd=1))*2

# 检验结果可视化
#####################################
x <- seq(-5,5,length.out = 100) # 随机变量X的可能取值,这里是IQ的可能取值
y <- dnorm(x,0,1) # 正态分布密度概率函数的高度
plot(x,y,type = "l")
#####################################

Z.5 <- qnorm(0.05/2,mean=0,sd = 1) # 计算p值为0.05时的Z统计量

abline(v = Z.5,col="red")
abline(v = -Z.5,col="red")

abline(v = -1.7182)
abline(v = 1.7182)


	Two-sample z-Test

data:  cityA and cityB
z = -1.7182, p-value = 0.08577
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -17.446925   1.146925
sample estimates:
mean of x mean of y 
   100.65    108.80 

	Two-sample z-Test

data:  cityB and cityA
z = 1.7182, p-value = 0.08577
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -1.146925 17.446925
sample estimates:
mean of x mean of y 
   108.80    100.65 
0.0857601415480858
0.0857601415480858

生信小木屋

生信小木屋