【问题标题】:How do I run this specific code 1000 times and save the results in a vector?如何运行此特定代码 1000 次并将结果保存在向量中?
【发布时间】:2020-05-26 08:40:44
【问题描述】:

我在这里有 while 循环,但我被困在如何运行这个循环 1000 次并将结果保存为向量 x,如果我能得到一些帮助,那就太好了!

n=1 
success = FALSE 
while(success == FALSE){ 
  n=n+1 #conditions
  if(rbinom(1, n, (n*n+1)^-1) == 1) 
    success = TRUE
  } 
n

【问题讨论】:

    标签: r algorithm loops


    【解决方案1】:

    编写代码以在函数中重复:

    run_function <- function(){
      n=1 
      success = FALSE
      while(!success){ 
        n=n+1
        if(rbinom(1, n, (n*n+1)^-1) == 1) 
           success = TRUE
        } 
        n
    }
    

    使用replicate 重复1000 次并将结果向量存储在x 中。

    x <- replicate(1000, run_function())
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2021-07-31
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2023-03-29
      • 2021-02-10
      • 2018-01-06
      相关资源
      最近更新 更多