Sample () isn't sampling randomly?

Can someone please explain what's going on here? I wanted to simulate 10,000 20-sided dice rolls. I used this code:

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

but that gives me the following:

hist(x)

      

Plot 1

The problem seems to be above 12: Plot 2Plot 3

What am I missing here? Thanks to

+3


source to share


1 answer


It doesn't really have anything to do with yours sample

, it 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 will notice it randomly. However, it hist

reproduces your graph. If you count the bars, you will notice that there are 19, not 20.



Try this instead:

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

      

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

enter image description here

+4


source







All Articles