You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言循环生成随机数时逻辑判断条件未生效问题求助

问题成因
  • 第一,条件判断不一致:你在repeat循环的终止条件里写的是any(a > 12 & b > 12),但后续截取首次满足条件的行时,误把判断条件写成了d_i$a > 10 & d_i$b > 10,最终提取到的是第一个两个数都大于10的行,而非大于12的行,这就是输出结果都小于12的核心原因。
  • 第二,生成组数统计逻辑错误:你当前的index只统计了最后一次生成的10000组里的位置,没有把之前未命中条件的批次的组数算进去,统计的总生成组数会严重偏小。
修复方案

以下提供两种可正常运行的实现:

逐对生成实现(逻辑直观不易出错)

完全贴合你“持续生成直到满足条件”的原始需求:

results <- data.frame(a = numeric(100), b = numeric(100), total_tries = integer(100), iteration = factor(1:100))

for (i in 1:100) {
  try_count <- 0
  # 循环生成直到满足a、b均大于12的条件
  repeat {
    try_count <- try_count + 1
    a <- rnorm(1, 10, 1)
    b <- rnorm(1, 10, 1)
    if (a > 12 & b > 12) {
      break
    }
  }
  # 存入当前迭代结果
  results[i, ] <- list(a = a, b = b, total_tries = try_count, iteration = as.factor(i))
}

批量生成优化实现(运行效率更高)

保留你原有的批量生成逻辑,同时修正判断条件和计数逻辑:

results <- list()

for (i in 1:100){
  total_count <- 0
  repeat {
    # 单次批量生成10000组随机数,减少循环次数
    a = rnorm(10000,10,1)
    b = rnorm(10000,10,1)
    # 查找当前批次第一个满足条件的位置
    hit_idx <- which(a > 12 & b > 12)[1]
    if (!is.na(hit_idx)) {
      # 命中条件,累计总生成组数后结束当前迭代
      total_count <- total_count + hit_idx
      d_i = data.frame(a = a[hit_idx], b = b[hit_idx], index = total_count, iteration = as.factor(i))
      break
    } else {
      # 未命中,累计当前批次全部组数后继续生成
      total_count <- total_count + 10000
    }
  }
  results[[i]] <- d_i
}

results_df <- do.call(rbind.data.frame, results)

内容的提问来源于stack exchange,提问作者stats_noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:15:02