-1

I have created a program that simulates the throwing of dice 100 times. I need help with adding up the results of the individual dice and also how to plot the probability distribution of outcomes.

This is the code I have:

sample(1:6, size=100, replace = TRUE)
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22

1 Answers1

0

So far, what you've done is sample the dice throws (note I've added a line setting the seed for reproducibility:

set.seed(123)
x <- sample(1:6, size=100, replace = TRUE)

The simple command to "add[] up the results of the individual dice" is table():

table(x)
# x
#  1  2  3  4  5  6 
# 17 16 20 14 18 15

Then, to "plot the probability distribution of outcomes," we must first get that distribution; luckily R provides the handy prop.table() function, which works for this sort of discrete distribution:

prop.table(table(x))
# x
#    1    2    3    4    5    6 
# 0.17 0.16 0.20 0.14 0.18 0.15 

Then we can easily plot it; for plotting PMFs, my preferred plot type is "h":

y <- prop.table(table(x))
plot(y, type = "h", xlab = "Dice Result", ylab = "Probability")

enter image description here

Update: Weighted die

sample() can easily used to simulate weighted die using its prob argument. From help("sample"):

Usage
sample(x, size, replace = FALSE, prob = NULL)

Arguments
[some content omitted]
prob      a vector of probability weights for obtaining the elements of the vector being sampled.

So, we just add your preferred weights to the prob argument and proceed as usual (note I've also upped your sample size from 100 to 10000):

set.seed(123)
die_weights <- c(4/37, rep(6/37, 4), 9/37)
x <- sample(1:6, size = 10000, replace = TRUE, prob = die_weights)
(y <- prop.table(table(x)))
# x
#      1      2      3      4      5      6 
# 0.1021 0.1641 0.1619 0.1691 0.1616 0.2412 
plot(y, type = "h", xlab = "Dice Result", ylab = "Probability")

enter image description here

duckmayr
  • 16,303
  • 3
  • 35
  • 53
  • Would you know how to simulate a loaded dice? One where the probability to roll a: 1 is 4/37, 2/3/4/5 is 6/37, 6 is 9/37? – user11301096 Apr 19 '19 at 09:33
  • @user11301096 Sure -- see the edited answer! It sounds like you're an R beginner. While it won't help you find the functions you need, you'll need to get really well acquainted with the `help()` function (or equivalently `?`), because it does help you learn about the functions you have heard of. Here, looking at `help("sample")` would have been the key: It teaches you about the `prob` argument, which is what you use to accomplish probability weighting. – duckmayr Apr 19 '19 at 10:36