【问题标题】:For loop or apply to save simulation results in a vector?For循环或应用以将模拟结果保存在向量中?
【发布时间】:2017-07-31 11:24:45
【问题描述】:

我的代码用于模拟 100 次抛硬币,如果您输掉 10 美元的本金,您就会破产(即,在 100 次抛硬币中净赢/输达到 -10,每次抛硬币是 1 美元的赌注)。我想运行 500 次,然后将盈亏结果保存到一个向量中。我的代码主要用于一次翻转,尽管我认为这可能不是最有效的方式 - 最好是添加一个 for 循环还是应用?

n=100
total.profit=c()
game.cashflow = cumsum(2*rbinom(n,1,prob=0.5)-1)
  if(length(game.cashflow[game.cashflow==-10])>0){
    game.profit=-10}else{
      game.profit=game.cashflow[1000]}

我想将结果保存在 total.profit 向量中。

【问题讨论】:

  • 看看replicate()

标签: r loops simulation apply


【解决方案1】:

这样的?

flipit <- function(n) {
    res <- sample(c(-1,1),n,replace=TRUE)
    ifelse(any(cumsum(res)<=-10),"bust",sum(res))
}

replicate(500,flipit(100))

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2017-07-03
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多