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

如何修改R脚本循环以累计20次tail(pvector,1)=1并统计0的次数

Solution to Track 20 Successful Fixation Runs & Count Failures

Got it, let's adjust your code to meet your goal: running simulations until we get 20 times where the final result is 1, while counting how many times the result was 0 before hitting that 20th success.

First, we'll keep your original evolve function since it's handling the core allele frequency calculation correctly. Then we'll wrap your simulation loop in an outer loop that tracks our success/failure counts.

Full Modified Code

# Keep your original evolve function - no changes needed here!
evolve = function(N,p0,s){
  tot.fit = p0*(1+s)+(1-p0)
  A.fit= p0*(1+s)
  return(rbinom(1,N,(A.fit/tot.fit))/N)
}

# Initialize counters for our tracking
success_count <- 0  # Number of times final result is 1
failure_count <- 0  # Number of times final result is 0

# Outer loop: run simulations until we hit 20 successes
while(success_count < 20) {
  # Reset variables for a new simulation run
  N <- 1000
  p <- 0.02
  pvector = c()
  
  # Your original inner simulation loop (runs until fixation at 0 or 1)
  while(p > 0 & p < 1) {  # Simplified equivalent of your original condition
    px <- evolve(N, p, 0.02)
    Nm <- 20
    p <- (N * px)/(N + Nm)
    pvector <- c(pvector, px)
  }
  
  # Get the final outcome of this simulation
  final_outcome <- tail(pvector, n=1)
  
  # Update counters based on the outcome
  if(final_outcome == 1) {
    success_count <- success_count + 1
  } else {
    failure_count <- failure_count + 1
  }
  
  # Optional: Print progress to see how we're doing
  cat(paste("Progress: Successes =", success_count, "| Failures =", failure_count, "\n"))
}

# Final result output
cat(paste("\nDone! We hit 20 successful fixation runs (result=1).\nNumber of failed runs (result=0) before the 20th success:", failure_count, "\n"))

Key Changes Explained

  • Outer Loop: This is the main driver that repeats your simulation until we have 20 successes. It keeps running as long as success_count is less than 20.
  • Counters: success_count and failure_count track how many times we've ended up with 1 or 0 respectively.
  • Simplified Inner Loop Condition: I changed p<1 & (1-p)<1 to p > 0 & p < 1—they're functionally identical, but this is easier to read (it just means "keep running until the allele is fixed at 0 or 1").
  • Progress Updates: The optional cat line lets you watch the simulation progress in real time, which is helpful since this might take a few runs to hit 20 successes.

Once the loop finishes, you'll get a clear output telling you how many times the result was 0 before reaching the 20th 1.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:14:33