I want to generate a random variable X by continuing generating U(0,1) random variables as long as their product falls below exp(-2). Then my random variable X would be equal to the number of U(0,1) random variables that was generated minus 1.
I tried using the while loop to do it but not sure why the code does not return anything in my console. Please help me point out what I did wrong?

p <- 1
counter <- 0

while(p < exp(-2)) {
  u <- runif(1)
  p <- p*u
  counter <- counter+1

  X <- counter - 1
  print(X)
}

推荐答案

update

如果要将该过程复制100次,可以使用replicate

replicate(
    100,
    {
        p <- 1
        counter <- 0
        repeat {
            p <- p * runif(1)
            counter <- counter + 1
            if (p < exp(-2)) {
                break
            }
        }
        counter
    }
)

我想你可以用repeat和条件p < exp(-2)

p <- 1
counter <- 0
repeat {
    print(counter)
    p <- p * runif(1)
    counter <- counter + 1
    if (p < exp(-2)) {
        print(counter)
        break
    }
}

R相关问答推荐

如何使用R Shiny中的条件面板仅隐藏和显示用户输入,同时仍允许运行基础计算?

带有叠加饼图系列的Highmap

通过使用str_detect对具有相似字符串的组进行分组

R for循环返回到先前值

如何直接从Fortran到R的数组大小?

是否可以创建一个ggplot与整洁判断的交互作用

可以替代与NSE一起使用的‘any_of()’吗?

我正在努力用R计算数据集中的中值逐步距离

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

从R中的对数正态分布生成随机数的正确方法

`夹心::vcovCL`不等于`AER::tobit`标准错误

根据另一列中的值和条件查找新列的值

如何平滑或忽略R中变量的微小变化?

在使用具有Bray-Curtis相似性的pvCluust时计算p值

通过初始的shiny 应用更新部署的shiny 应用的数据和参数,其中部署的应用程序显示为URL

如何显示准确的p值而不是<;0.001*?

访问数据帧中未定义的列时出现R错误

在REST API中使用参数R

带有Bootswatch Cerulean主题的shiny 仪表板中的浏览&按钮可见性问题

如何阅读带有方括号的文件?