分组后变量Bootstrap置信区间求解报错及需求咨询
First, adjust your approach to use a helper function that computes the median and BCA bootstrap CI for a single vector, then apply this function to each group using summarise (not mutate):
# Load required packages library(boot) library(dplyr) # Define bootstrap statistic function mediana_boot <- function(x, i) median(x[i]) # Helper function to calculate median and BCA confidence interval compute_boot_ci <- function(data_vector) { # Run bootstrap with 1000 replicates (increase for more reliable results) boot_result <- boot(data_vector, mediana_boot, R = 1000) # Compute BCA confidence interval ci_result <- boot.ci(boot_result, conf = 0.95, type = "bca") # Extract values and return as a tibble tibble( mediana = median(data_vector), CI.L = ci_result$bca[4], CI.U = ci_result$bca[5] ) } # Apply to grouped data result <- lr2_analysis_CO_FIL %>% filter(BARRIER_POS != 'no_street') %>% group_by(BARRIER_POS) %>% summarise(compute_boot_ci(R_CO_GC)) %>% ungroup() # View the final result (includes BARRIER_POS, median, and CI bounds) print(result)
Why Your Original Code Failed
Using
mutateinstead ofsummarise:mutatetries to add a column to every row in the group, meaning the bootstrap runs once per row (redundant and inefficient). This triggers the recursive promise evaluation error because the code repeatedly references group-level data for each row.summariseis designed to produce one result per group, which matches your goal.Incorrect CI extraction:
Theboot.cioutput is a list structure. Your original code usedboot_CO[4]andboot_CO[5], which doesn't correctly target the BCA interval values. You need to access thebcaelement of theboot.ciresult—a matrix where the 4th and 5th entries are the 95% lower and upper bounds.Unnecessary
data.frame()call:
The finaldata.frame(mediana, CI.L, CI.U)incorrectly referenced variables outside the summarise environment, contributing to the recursive error.summarisealready retains theBARRIER_POSgrouping column, so this step was redundant.
内容的提问来源于stack exchange,提问作者Heidel Moronta

