随机抽样
1.有放回抽样与无放回抽样
#x为总体向量 n为样本容量
#replace=F表示无放回抽样 replace=T表示放回抽样
#prob可以设置不等概率抽样
#sample(x,n, replace = F, prob = NULL)
># 用R模拟掷硬币 H表示正面 T表示反面 有放回抽样
> sample(c('H','T'),10,replace=T)
[1] "H" "T" "T" "T" "T" "H" "T" "H" "T" "T"
>
> a <- as.vector(outer(1:6,1:6,paste))# 模拟掷两个骰子所有可能的结果
> a
[1] "1 1" "2 1" "3 1" "4 1" "5 1" "6 1" "1 2" "2 2" "3 2"
[10] "4 2" "5 2" "6 2" "1 3" "2 3" "3 3" "4 3" "5 3" "6 3"
[19] "1 4" "2 4" "3 4" "4 4" "5 4" "6 4" "1 5" "2 5" "3 5"
[28] "4 5" "5 5" "6 5" "1 6" "2 6" "3 6" "4 6" "5 6" "6 6"
> sample(a,10,replace=T)# 模拟掷两个骰子十次
[1] "5 3" "2 3" "1 3" "4 4" "6 1" "5 1" "2 1" "6 4" "1 5"
[10] "2 6"
>
2.Bootstrap重抽样
> x <- round(rnorm(300,100,12)) #随机生成一组原始数据
> y <- sample(x,1000,replace = T)#对原始数据进行bootstrap重抽样
> par(mfrow=c(1,2)) #设置绘图窗口为 1 x 2
> hist(x,breaks=16,col=gray(.9),main='histogram of source data') #绘制原始数据直方图
> hist(y,breaks=16,col=gray(.9),main='histogram of bootstrap example') #绘制bootstrap样本直方图
>
结果如下图:
可以发现,bootstrap重抽样之后的样本绘制的直方图较接近原始数据的直方图