抽样和假设检测(t检测之单样本T检测)
抽样
抽样函数sample
举例:
> x=1:12
#sample函数从x中随机抽出12个数
> sample(x)
[1] 3 1 2 6 10 11 8 9 4 5 12 7
#replace表示抽取的数字是否可以重复,true为可以重复(抽样可以放回)
> sample(x,replace=TRUE)
[1] 12 11 7 12 3 3 10 5 2 2 6 9
#replace=false表示抽取的数字不能重复(抽样不可以放回)
> sample(x,replace=FALSE)
[1] 5 8 3 1 2 4 9 6 10 11 12 7
#z向量0,1中随机抽取100个数字,可以重复
> sample(c(0,1),100,replace=TRUE)
[1] 0 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 1 0 1 1 1 0 1 0 0
[30] 1 1 1 1 1 0 0 1 0 1 1 0 1 0 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1
[59] 1 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 1 1 1 1 0 1 1 1 0 1
[88] 0 0 0 1 0 1 0 0 0 1 1 0 1
#1e1?表示1*10^1=10,e是科学计数法符号
> dic1=sample(1:2,1e1,replace=T)
> dic1
[1] 2 1 1 1 1 2 1 1 2 2
>
-计算三个骰子点数和的分布
> dic1=sample(1:6,1e6,replace=T)
> dic2=sample(1:6,1e6,replace=T)
> dic3=sample(1:6,1e6,replace=T)
> dicsum=dic1+dic2+dic3
> table(dicsum)
dicsum
3 4 5 6 7 8
4695 13969 27655 46168 69345 96533
9 10 11 12 13 14
116107 124696 125944 115861 97051 69391
15 16 17 18
46151 27887 14009 4538
> mean(dicsum==3)
[1] 0.004695
#barplot 函数用于绘制柱状图
> barplot(table(dicsum))
从一个分布中抽样
正太分布
#100个均值为0,方差为10的随机数
> rnorm(100,0,10)
[1] 5.91258263 4.60607828 -2.53421708
[4] 8.29726071 0.63896198 -14.06398260
[7] -1.18781085 -6.59500046 4.07381222
..... .... .......
t分布
#100个自由度为3的随机数
> rt(100,df=3)
[1] 0.47765937 -0.23718475 1.33055857
[4] 2.31754129 2.97899007 -0.80741669
[7] 0.54888585 0.50405830 2.39647974
..... .... .......
均匀分布
#100个在-10到10之间的随机数
> runif(100,-10,10)
[1] 4.6019036 -2.3467617 8.1311114
[4] 8.0048959 5.3545532 -7.6249559
[7] 4.1327952 -5.2932179 6.0708005
..... .... .......
在均匀分布中多次抽样,样本均值的分布如何?
#设置种子相当于设置定向抽样
> set.seed(123)
#由于前面设置了种子,所以x每次所抽到的随机数是一样的。
> x=runif(n=1e4,0,10)
#每次结果的平均值是不变的
> mean(x)
[1] 4.975494
#每次的标准差也是不变的。
> sd(x)
[1] 2.866937
>
接下来我们进入昨天交代的关键内容
假设检验
检验某个假设步骤:
1. - 原假设H0 ,- 备选假设H1
——— 通常情况下,H0是假设相等的。
2.输出:
-p>0.05:H0
-p<0.05:H1
T检验
-单样本T检测
Wage数据中大学学历的收入是100?
> View(Wage)
如上图,红圈内是 学历,黑圈内是薪水
我们取4.College Grad作为大学学历
#取包
> library(ISLR)
#取数据集
> data(Wage)
#取Wage数据集中的'wage'子串
> x=subset(Wage,education=='4. College Grad',select='wage')
#t检验,miu为均值参数,即原假设中设定的参数alternative='greater'是对立假设是大于号
> t.test(x,miu=100,alternative='greater')
One Sample t-test
data: x
t = 79.064, df = 684, p-value < 2.2e-16
alternative hypothesis: true mean is greater than 0
#95%置信水平落在[121.8358,Inf]置信区间内
#且上面的0(对立假设)并不在置信区间内
95 percent confidence interval:
121.8358 Inf
sample estimates:
mean of x
124.4279
以上p值<0.05,拒绝原假设,说明大学学历的收入并不是100。
今天就先到这里吧,我们明天继续讲解哈~