# 【数据分析 R语言实战】学习笔记 第六章 参数估计与R实现（下）

6.3两正态总体的区间估计

(1)两个总体的方差已知

`> twosample.ci=function(x,y,alpha,sigma1,sigma2){+ n1=length(x);n2=length(y)+ xbar=mean(x)-mean(y)+ z=qnorm(1-alpha/2)*sqrt(sigma1^2/n1+sigma2^2/n2)+ c(xbar-z,xbar+z)+ }`

Bamberger's是一家为社区提供大众性商品的零传商店，为了努力维持商店的良好声誉，公司实施了将营业时间延长至夜间的计划。以Bamberger's延长营业时间前后27个典型周的销售额数据为例(以万元为单位)，计算这两个样本均值差的区间估计，从而可以看出计划实施后的效果。首先查看数据的基本类型，并绘制直方图对比。

`> sales=read.table("D:/Program Files/RStudio/sales.txt",header=T)> head(sales)prior post1 67.90 86.102 76.12 71.133 68.64 116.254 74.94 102.605 63.32 97.516 50.43 65.39> attach(sales)> par(mfrow=c(1,2))> hist(prior) #分别绘制计划前后销售额的直方图> hist(post)`

`> twosample.ci(post,prior,alpha=0.05,8,12)[1] 19.10298 29.98295> z.test(post,prior,sigma.x=8,sigma.y=12)\$conf.int[1] 19.10298 29.98295attr(,"conf.level")[1] 0.95`

(2)两个总体的方差未知但相等

`> t.test(post,prior,var.equal=TRUE)\$conf.int[1] 18.66541 30.42051attr(,"conf.level")[1] 0.95`

(3) 两个总体的方差未知且不等

R中也没有直接的函数可用，仍需要手动写出一个函数twasarnple.ci2()

`> twosample.ci2=function(x,y,alpha){+ n1=length(x);n2=length(y)+ xbar=mean(x)-mean(y)+ S1=var(x);S2=var(y)+ nu=(S1/n1+S2/n2)^2/(S1^2/n1^2/(n1-1)+S2^2/n2^2/(n2-1))+ z=qt(1-alpha/2,nu)*sqrt(S1/n1+S2/n2)+ c(xbar-z,xbar+z)+ }`

`> twosample.ci2(post,prior,0.05)[1] 18.63821 30.44771`

6.3.2两方差比的区间估计

`var.test(x, y, ratio = 1,alternative = c("two.sided", "less", "greater"),conf.level = 0.95, ...)> var.test(prior,post)\$conf.int[1] 0.1772458 0.8534348attr(,"conf.level")[1] 0.95`

6.4关于比率的区间估计

prop.test(x, n, p = NULL,

alternative = c("two.sided", "less", "greater"),

conf.level = 0.95, correct = TRUE)

`> prop.test(214,2000)1-sample proportions test with continuitycorrectiondata: 214 out of 2000, null probability 0.5X-squared = 1234, df = 1, p-value < 2.2e-16alternative hypothesis: true p is not equal to 0.595 percent confidence interval:0.09396256 0.12157198sample estimates:p0.107`

`> binom.test(214,2000)Exact binomial testdata: 214 and 2000number of successes = 214, number of trials =2000, p-value < 2.2e-16alternative hypothesis: true probability of success is not equal to 0.595 percent confidence interval:0.09378632 0.12137786sample estimates:probability of success0.107`

Top