简体   繁体   English

在 R 中绘制蒙特卡罗模拟

[英]plotting a Monte Carlo simulation in R

I am trying to create a plot that graph a Monte Carlo simulation of a coin toss with iterations on x and probability on y.我正在尝试创建一个 plot 来绘制硬币抛掷的蒙特卡罗模拟,其中 x 上的迭代和 y 上的概率。 However, I am having difficulty creating the necessary function.但是,我很难创建必要的 function。

So far I have到目前为止我有

set.seed(2738952)
coins<-function(n){
    sample(c(0,1),n,replace=TRUE)
}
mean(coins(10000)==1)

ggplot(mapping = aes(x=iteration,y=coins))+geom_line()

Error: Aesthetics must be valid data columns.错误:美学必须是有效的数据列。 Problematic aesthetic(s): y = coins.有问题的美学:y = 硬币。 Did you mistype the name of a data column or forget to add stat()?您是否输入错误数据列的名称或忘记添加 stat()?

I am unsure how to create the iterations as well as the probability.我不确定如何创建迭代以及概率。

Is this something you're looking for?这是你要找的东西吗?

iterations <- 100
flip_results <- coins(iterations)
# As @teunbrand suggested, use cumsum to avoid looping
pct_head <- pct_head <- cumsum(flip_results) / seq_len(iterations)
ggplot(mapping = aes(x=1:iterations,y=pct_head))+geom_line()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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