0
votes

what im trying to solve is simulation of dice roll and it goes as follows:

  • numbers are default for dice 1,2,3,4,5,6 and it follows probability distribution of {0.15,0.15,0.2,0.2,0.2,0.1}
  • set.seed is 555
  • there will be 100 rolls
  • result should be in mean from numbers that were given

Here is what i did:

set.seed(555)
sample(1:6, size = 100, prob = c(0.15,0.15,0.2,0.2,0.2,0.1), replace = TRUE)
#and previous one gives me result of 
[1] 5 2 1 4 1 3 6 5 3 2 2 5 4 4 6 1 4 3 1 6 5 3 5 5 3 4 3 6 5 3 4 5 1 5 5 5 3 5 1 5 2 4 1 1 3 3
[47] 2 3 3 3 4 3 1 3 4 5 4 5 6 2 4 3 5 3 1 2 4 4 5 1 4 3 5 1 1 2 5 1 3 5 6 6 6 2 2 2 5 4 3 1 1 5
[93] 1 6 5 2 6 5 3 1

Now issue is what i have is that i dont understand how can you get mean out of this number or what function to use. I know that rnorm and mean are used but i do not understand how.

2

2 Answers

2
votes

The expected value (i.e. the mean of an infinite number of throws) will just be:

sum(1:6 * c(0.15,0.15,0.2,0.2,0.2,0.1))
# [1] 3.45

If you want to do it as a simulation of 100 rolls you can do this:

set.seed(555)
sample1 <- sample(1:6, size = 100, prob = c(0.15,0.15,0.2,0.2,0.2,0.1), replace = TRUE)

Now you can examine the sample and take its mean:

sample1
#  [1] 5 2 1 4 1 3 6 5 3 2 2 5 4 4 6 1 4 3 1 6 5 3 5 5 3 4 3 6 5 3 4 5 1 5 5 5 3 5 1 5
# [41] 2 4 1 1 3 3 2 3 3 3 4 3 1 3 4 5 4 5 6 2 4 3 5 3 1 2 4 4 5 1 4 3 5 1 1 2 5 1 3 5
# [81] 6 6 6 2 2 2 5 4 3 1 1 5 1 6 5 2 6 5 3 1
mean(sample1)
# [1] 3.45

If you want to get really fancy, you can simulate your 100 dice throws thousands of times and plot the results, all with a single line of code:

 hist(sapply(1:1000, function(x) mean(sample(1:6, size = 100, prob = c(0.15,0.15,0.2,0.2,0.2,0.1), replace = TRUE))), main = "Means of 100 throws (n = 1000)", xlab = "mean")

enter image description here

2
votes

Here is the code you can use, including both empirical mean and theoretical mean

set.seed(555)
p <- c(0.15,0.15,0.2,0.2,0.2,0.1)
res <- sample(1:6, size = 100, prob = p, replace = TRUE)
# empirical mean
mean_empirical <- mean(res)
# theoretical mean
mean_theoretical <- seq(6)%*%t(t(p))

Additional

  • If you want to view the distribution of mean values of 100 rolls, you can repeat the event (mean of rolling dice 100 times) by many times, e.g., 100000 times, then you can try the following code (using replicate)
r <- replicate(100000,mean(sample(1:6, size = 100, prob = p, replace = TRUE)))
barplot(prop.table(table(r)))

enter image description here - If you want to view the empirical distribution of res, you can use the following line (using prop.table() + table())

barplot(prop.table(table(res)))

enter image description here