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

如何用循环实现多次随机抽样并生成行均值汇总数据框?

重复抽样与均值列汇总实现方案

一、重复100次抽样并生成带均值列的数据集

推荐方法:用列表统一管理(更整洁,避免变量泛滥)

直接把每次抽样的结果存入列表,不用单独创建100个变量,后续处理更方便:

# 初始化空列表,长度设为100
sampled_list <- vector("list", 100)

for (i in 1:100) {
  # 随机抽取200行(用nrow(df)代替硬编码9000,更灵活)
  sample_idx <- sample(1:nrow(df), 200, replace = FALSE)
  sampled_df <- df[sample_idx, ]
  # 添加对应序号的行均值列
  sampled_df[[paste0("Means_", i)]] <- rowMeans(sampled_df)
  # 将结果存入列表
  sampled_list[[i]] <- sampled_df
}

用assign实现变量命名(按你的需求)

如果一定要生成sampled_df_1到sampled_df_100这类单独变量,可以这么写:

for (i in 1:100) {
  sample_idx <- sample(1:nrow(df), 200, replace = FALSE)
  sampled_df <- df[sample_idx, ]
  sampled_df[[paste0("Means_", i)]] <- rowMeans(sampled_df)
  # 拼接变量名并赋值
  assign(paste0("sampled_df_", i), sampled_df)
}

二、快速汇总所有均值列到新数据框

针对列表存储的情况(更高效)

直接从列表里提取每个数据框的均值列,合并成新数据框:

# 遍历列表,提取所有以Means_开头的列并合并
mean_cols_df <- do.call(cbind, lapply(sampled_list, function(x) {
  x[, grepl("^Means_", colnames(x))]
}))

针对assign生成的单独变量情况

先找出所有目标变量,再提取均值列合并:

# 找出所有以sampled_df_开头的变量名
target_dfs <- ls(pattern = "^sampled_df_")
# 提取每个变量的均值列并合并
mean_cols_df <- do.call(cbind, lapply(target_dfs, function(name) {
  current_df <- get(name)
  current_df[, grepl("^Means_", colnames(current_df))]
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:35:25