如何用R循环重复执行抽样与调查分析代码30次?
Repeating SRS Sampling & Analysis 30 Times Automatically in R
Hey Paola, great question—manually writing that code 30 times would be such a tedious hassle. Let’s use R’s built-in tools to automate this process smoothly. Since your code relies on the survey package, here are two reliable, easy-to-implement approaches:
Approach 1: Using a for Loop (Intuitive for Beginners)
This method is straightforward and easy to follow, perfect if you prefer explicit, step-by-step logic. We’ll loop through 30 iterations, run your sampling/analysis each time, and store all results for later review.
Full Code:
# Load the required package (install first if you haven't: install.packages("survey")) library(survey) # Initialize empty lists to store our 30 sets of results total_estimates <- vector("list", 30) mean_estimates <- vector("list", 30) # Define your population size (used in the finite population correction) population_size <- 6399875 # Run the loop 30 times for (i in 1:30) { # Step 1: Draw a 10% SRS sample from your data srs_indices <- sample(1:nrow(MyData_points), size = 0.10 * nrow(MyData_points)) sampled_data <- MyData_points[srs_indices, ] # Step 2: Set up FPC (note: we use nrow(sampled_data) to match the actual sample size each time) fpc_values <- rep(population_size, nrow(sampled_data)) # Step 3: Create the survey design object srs_design <- svydesign(id = ~1, strata = NULL, data = sampled_data, fpc = fpc_values) # Step 4: Calculate total and mean, then store the results total_estimates[[i]] <- svytotal(~V4, design = srs_design) mean_estimates[[i]] <- svymean(~V4, design = srs_design) # Optional: Print progress to track how many iterations are done cat("Finished iteration", i, "\n") } # Convert results to data frames for easier analysis (e.g., calculating averages of estimates) total_results_df <- do.call(rbind, lapply(total_estimates, as.data.frame)) mean_results_df <- do.call(rbind, lapply(mean_estimates, as.data.frame))
Approach 2: Using purrr (Cleaner for Tidyverse Users)
If you’re comfortable with the tidyverse ecosystem, using purrr::map lets you write more concise, function-focused code without explicit loops.
Full Code:
library(survey) library(purrr) library(dplyr) # Define a function that runs one complete iteration of your sampling/analysis run_single_srs <- function() { # Draw sample srs_indices <- sample(1:nrow(MyData_points), size = 0.10 * nrow(MyData_points)) sampled_data <- MyData_points[srs_indices, ] # Set up FPC and survey design fpc_values <- rep(6399875, nrow(sampled_data)) srs_design <- svydesign(id = ~1, strata = NULL, data = sampled_data, fpc = fpc_values) # Return both total and mean estimates in a list list( total_estimate = svytotal(~V4, design = srs_design), mean_estimate = svymean(~V4, design = srs_design) ) } # Run the function 30 times all_srs_results <- map(1:30, ~run_single_srs()) # Extract and convert results to tidy data frames total_results_df <- all_srs_results %>% map("total_estimate") %>% map_dfr(as.data.frame) mean_results_df <- all_srs_results %>% map("mean_estimate") %>% map_dfr(as.data.frame)
Key Tips:
- FPC Adjustment: Your original code uses
rep(6399875, 639987)—I updated both approaches to usenrow(sampled_data)instead, which ensures the FPC vector always matches your actual sample size (critical if your data’s row count isn’t perfectly divisible by 10). - Result Analysis: Once you have the results in data frames, you can easily calculate summary stats (like the average of all 30 total estimates, or their standard deviation) to assess how much your estimates vary across samples.
- Package Checks: Make sure you have all required packages installed before running the code—use
install.packages(c("survey", "purrr", "dplyr"))if needed.
内容的提问来源于stack exchange,提问作者Paola
相关产品推荐
相关产品推荐

