How to repeat a random sample in R?



The random sample can be repeated by using replicate function in R. For example, if we have a vector that contains 1, 2, 3, 4, 5 and we want to repeat this random sample five times then replicate(5,x) can be used and the output will be matrix of the below form:

[,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

Example 1

Live Demo

> x1<-sample(0:1,10,replace=TRUE)
> x1

Output

[1] 1 0 1 0 1 1 1 0 0 1

Example

> replicate(2,x1)

Output

[,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

Example 2

Live Demo

> x2<-rnorm(20,5,0.43)
> x2

Output

[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

Example

> replicate(4,x2)

Output

[,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

Example 3

Live Demo

> x3<-rpois(20,5)
> x3

Output

[1] 8 4 5 3 4 3 4 3 8 3 2 6 5 6 4 7 6 2 2 2

Example

> replicate(8,x3)

Output

[,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

Example4

Live Demo

> x4<-sample(c("A","B","c","d"),10,replace=TRUE)
> x4

Output

[1] "B" "A" "B" "A" "c" "B" "d" "A" "d" "d"

Example

> replicate(5,x4)

Output

[,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"

Advertisements