我不知道如何绘制 R 中某些代码结果的概率分布
I do not know how to plot the probability distribution of outcomes of some code in R
我创建了一个模拟掷骰子 100 次的程序。我需要有关将单个骰子的结果相加以及如何绘制结果的概率分布的帮助。
这是我的代码:
sample(1:6, size=100, replace = TRUE)
到目前为止,您所做的是对掷出的骰子进行采样(请注意,我添加了一行设置种子的可重复性:
set.seed(123)
x <- sample(1:6, size=100, replace = TRUE)
"add[] up the results of the individual dice" 的简单命令是 table()
:
table(x)
# x
# 1 2 3 4 5 6
# 17 16 20 14 18 15
那么,为了"plot the probability distribution of outcomes,"我们必须先得到那个分布;幸运的是 R 提供了方便的 prop.table()
函数,它适用于这种离散分布:
prop.table(table(x))
# x
# 1 2 3 4 5 6
# 0.17 0.16 0.20 0.14 0.18 0.15
然后我们就可以轻松绘制出来了;对于绘制 PMF,我首选的绘图类型是 "h"
:
y <- prop.table(table(x))
plot(y, type = "h", xlab = "Dice Result", ylab = "Probability")
更新:加权骰子
sample()
可以很容易地使用其 prob
参数来模拟加权骰子。来自 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.
因此,我们只需将您的首选权重添加到 prob
参数并照常进行(请注意,我还将您的样本量从 100 增加到 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")
我创建了一个模拟掷骰子 100 次的程序。我需要有关将单个骰子的结果相加以及如何绘制结果的概率分布的帮助。
这是我的代码:
sample(1:6, size=100, replace = TRUE)
到目前为止,您所做的是对掷出的骰子进行采样(请注意,我添加了一行设置种子的可重复性:
set.seed(123)
x <- sample(1:6, size=100, replace = TRUE)
"add[] up the results of the individual dice" 的简单命令是 table()
:
table(x)
# x
# 1 2 3 4 5 6
# 17 16 20 14 18 15
那么,为了"plot the probability distribution of outcomes,"我们必须先得到那个分布;幸运的是 R 提供了方便的 prop.table()
函数,它适用于这种离散分布:
prop.table(table(x))
# x
# 1 2 3 4 5 6
# 0.17 0.16 0.20 0.14 0.18 0.15
然后我们就可以轻松绘制出来了;对于绘制 PMF,我首选的绘图类型是 "h"
:
y <- prop.table(table(x))
plot(y, type = "h", xlab = "Dice Result", ylab = "Probability")
更新:加权骰子
sample()
可以很容易地使用其 prob
参数来模拟加权骰子。来自 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.
因此,我们只需将您的首选权重添加到 prob
参数并照常进行(请注意,我还将您的样本量从 100 增加到 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")