如何在 R 中重复随机样本?
随机样本可以通过 R 中的复制函数来重复。例如,如果我们有一个包含 1、2、3、4、5 的向量,并且我们希望重复这个随机样本五次,则可以使用 replicate(5,x),输出将是如下形式的矩阵
[,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 2 2 2 2 2 [3,] 3 3 3 3 3 [4,] 4 4 4 4 4 [5,] 5 5 5 5 5
示例 1
> x1<-sample(0:1,10,replace=TRUE) > x1
输出
[1] 1 0 1 0 1 1 1 0 0 1
示例
> replicate(2,x1)
输出
[,1] [,2] [1,] 1 1 [2,] 0 0 [3,] 1 1 [4,] 0 0 [5,] 1 1 [6,] 1 1 [7,] 1 1 [8,] 0 0 [9,] 0 0 [10,] 1 1
示例 2
> x2<-rnorm(20,5,0.43) > x2
输出
[1] 4.946766 4.930826 4.845512 4.940984 5.091849 5.437576 5.438818 4.319041 [9] 5.294105 4.941349 5.895272 5.161996 4.541355 5.065261 5.065255 4.770162 [17] 4.575399 4.466801 4.814925 5.568215
示例
> replicate(4,x2)
输出
[,1] [,2] [,3] [,4] [1,] 4.946766 4.946766 4.946766 4.946766 [2,] 4.930826 4.930826 4.930826 4.930826 [3,] 4.845512 4.845512 4.845512 4.845512 [4,] 4.940984 4.940984 4.940984 4.940984 [5,] 5.091849 5.091849 5.091849 5.091849 [6,] 5.437576 5.437576 5.437576 5.437576 [7,] 5.438818 5.438818 5.438818 5.438818 [8,] 4.319041 4.319041 4.319041 4.319041 [9,] 5.294105 5.294105 5.294105 5.294105 [10,] 4.941349 4.941349 4.941349 4.941349 [11,] 5.895272 5.895272 5.895272 5.895272 [12,] 5.161996 5.161996 5.161996 5.161996 [13,] 4.541355 4.541355 4.541355 4.541355 [14,] 5.065261 5.065261 5.065261 5.065261 [15,] 5.065255 5.065255 5.065255 5.065255 [16,] 4.770162 4.770162 4.770162 4.770162 [17,] 4.575399 4.575399 4.575399 4.575399 [18,] 4.466801 4.466801 4.466801 4.466801 [19,] 4.814925 4.814925 4.814925 4.814925 [20,] 5.568215 5.568215 5.568215 5.568215
示例 3
> x3<-rpois(20,5) > x3
输出
[1] 8 4 5 3 4 3 4 3 8 3 2 6 5 6 4 7 6 2 2 2
示例
> replicate(8,x3)
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 8 8 8 8 8 8 8 8 [2,] 4 4 4 4 4 4 4 4 [3,] 5 5 5 5 5 5 5 5 [4,] 3 3 3 3 3 3 3 3 [5,] 4 4 4 4 4 4 4 4 [6,] 3 3 3 3 3 3 3 3 [7,] 4 4 4 4 4 4 4 4 [8,] 3 3 3 3 3 3 3 3 [9,] 8 8 8 8 8 8 8 8 [10,] 3 3 3 3 3 3 3 3 [11,] 2 2 2 2 2 2 2 2 [12,] 6 6 6 6 6 6 6 6 [13,] 5 5 5 5 5 5 5 5 [14,] 6 6 6 6 6 6 6 6 [15,] 4 4 4 4 4 4 4 4 [16,] 7 7 7 7 7 7 7 7 [17,] 6 6 6 6 6 6 6 6 [18,] 2 2 2 2 2 2 2 2 [19,] 2 2 2 2 2 2 2 2 [20,] 2 2 2 2 2 2 2 2
示例 4
> x4<-sample(c("A","B","c","d"),10,replace=TRUE) > x4
输出
[1] "B" "A" "B" "A" "c" "B" "d" "A" "d" "d"
示例
> replicate(5,x4)
输出
[,1] [,2] [,3] [,4] [,5] [1,] "B" "B" "B" "B" "B" [2,] "A" "A" "A" "A" "A" [3,] "B" "B" "B" "B" "B" [4,] "A" "A" "A" "A" "A" [5,] "c" "c" "c" "c" "c" [6,] "B" "B" "B" "B" "B" [7,] "d" "d" "d" "d" "d" [8,] "A" "A" "A" "A" "A" [9,] "d" "d" "d" "d" "d" [10,] "d" "d" "d" "d" "d"
广告