Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sample() not sampling randomly? [duplicate]

Tags:

r

Can someone explain whats going wrong here? I wanted to simulate 10,000 20-sided dice rolls. I used this code:

x <- sample(1:20,10000,replace=T)

but that give me this:

hist(x)

Plot 1

It seems to be a problem above 12: Plot 2 Plot 3

What am I not understanding here? Thanks

like image 995
Adam C Avatar asked Sep 08 '26 03:09

Adam C


1 Answers

It's not actually to do with your sample, it's hist.

If you do this

set.seed(1)
x <- sample(1:20,10000,replace=T)
table(x)

  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
513 522 482 495 459 549 506 505 518 498 495 492 440 490 459 509 496 528 511 533 

you'll notice it's random. However hist reproduces your graph. If you count the bars you'll notice there are 19 and not 20.

Trying this instead:

bins <- seq(0, 20, by=1)
hist(x, breaks=bins)

gives a graph with even bar heights because all 20 bars are shown (i.e. 1 and 2 are not collapsed together).

enter image description here

like image 188
jalapic Avatar answered Sep 10 '26 20:09

jalapic