0

I want to simulate an experiment where you throw a fair dice 100 times and count the number of ones. I want to repeat this experiment 10^5 times and save the outcomes.

Here is my code to throw a dice n times

dice <- function(n) {
   sample(c(1:6),n,replace = TRUE)
}

x <- dice(100)

Next, I want to count the number of 1's and do the simulation 10^5 times (this part is wrong):

x <- numeric(10^5)

for(n in 1:10^5){
  x[n] <- sum(dice(100)) 
} 

hist(x,
  main="100 Fair Rolls",
  xlab="Rolls",
  ylab="Probability",
  xlim=c(0,100),
  breaks=-1:1000+1,
  prob=TRUE)
Cettt
  • 11,460
  • 7
  • 35
  • 58
JaredJoss
  • 19
  • 3

2 Answers2

1

You were very close I think. If you change your for loop as follows it should work.

for(n in 1:10^5){

  x[n]<-sum(dice(100)==1) 

} 
olorcain
  • 1,230
  • 1
  • 9
  • 12
  • Thank you very much! Would you know how to do a bell curve over that histogram? – JaredJoss Apr 23 '19 at 18:03
  • I haven't done that before. Looking at this thread, stat_function seems to be the solution - https://stackoverflow.com/questions/29182228/plotting-normal-curve-over-histogram-using-ggplot2-code-produces-straight-line?rq=1 – olorcain Apr 23 '19 at 19:16
0

if you compute sum(dice(100)) you get the sum of all outcomes not only the ones. Instead you should only return the elements of your experiment which contains 1:

dice <- function(n) {
   x <- sample(c(1:6), n, replace = TRUE)
   length(x[x==1])
}

Then you can use replicate which runs faster than a for loop:

x <- replicate(10^5, dice(100))
Cettt
  • 11,460
  • 7
  • 35
  • 58