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

使用for循环生成1000个随机样本,结果收集变量仅存单值的问题求助

问题修复方案

你的代码核心问题是每次循环都用单个值直接覆盖收集对象,没有把新结果追加进去,所以最终只保留了最后一次循环的结果。以下是两种修复方式:

方式1:追加式收集(简单直观)

直接在每次循环中用c()把新结果追加到收集向量末尾:

reject_collect <- NULL
CI_include_collect <- NULL
alpha <- 0.05  # 把alpha提到循环外,避免重复定义

for (i in 1:1000) { 
  random_vector_index <- rnorm(50, mean = 10, sd = 2)
  test_results_index <- t.test(random_vector_index, mu=10, 
                               alternative = "two.sided", 
                               conf.level = 0.95)
  
  # 用c()追加新结果,而不是直接覆盖
  reject_collect <- c(reject_collect, test_results_index$p.value < alpha)
  CI_include_collect <- c(CI_include_collect, 
                          between(10, test_results_index$conf.int[1], test_results_index$conf.int[2]))
}

方式2:预先初始化向量(更高效)

对于1000次循环,预先定义好长度为1000的逻辑向量,通过索引赋值,避免每次追加时的内存重新分配,效率更高:

# 预先初始化长度为1000的逻辑向量
reject_collect <- logical(1000)
CI_include_collect <- logical(1000)
alpha <- 0.05

for (i in 1:1000) { 
  random_vector_index <- rnorm(50, mean = 10, sd = 2)
  test_results_index <- t.test(random_vector_index, mu=10, 
                               alternative = "two.sided", 
                               conf.level = 0.95)
  
  # 通过索引i赋值,直接替换对应位置的元素
  reject_collect[i] <- test_results_index$p.value < alpha
  CI_include_collect[i] <- between(10, test_results_index$conf.int[1], test_results_index$conf.int[2])
}

额外优化:把alpha的定义移到循环外,避免每次循环重复创建相同变量,减少不必要的计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:10:26