简体   繁体   中英

I do not know how to plot the probability distribution of outcomes of some code in R

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)

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")

在此处输入图片说明

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM