R语言中自定义函数foo的Bootstrap实现报错求助
Fixing "number of items to replace is not a multiple of replacement length" in
boot::boot The Root Cause
Your error stems from inconsistent output length of your foo() function across Bootstrap resamples. Here's the breakdown:
- When you run
foo(dat)on your original data, it returns a vector with length equal to the number of unique values indat(1,2,3,4 → 4 values). - But during Bootstrap resampling, some resampled datasets might miss one or more of these unique values. For example, a resample could have no rows with value 2, so
foo(resample)would only return 3 values. - The
bootpackage requires the statistic function (boot_fun) to return a vector of fixed length every time. Mismatched lengths trigger that replacement error.
The Fix
We need to modify foo() to always return a vector with length matching the unique values from your original dataset—even if a resample is missing some values. Here's how to adjust your code:
- First, define the fixed set of unique values from your original data to use as reference levels.
- Update
foo()to accept afixed_levelsparameter, ensuring we always factorize values against this fixed set. - Modify
boot_funto pass these fixed levels tofoo()during each resample.
Modified Code
library(boot) # Updated foo function with fixed levels parameter foo <- function(X, fixed_levels) { X <- as.matrix(X) # Use fixed_levels instead of deriving from X to keep columns consistent tab <- table(row(X), factor(X, levels = fixed_levels)) w <- diag(ncol(tab)) rosum <- rowSums(tab) obs_oc <- tab * (t(w %*% t(tab)) - 1) obs_c <- colSums(obs_oc) max_oc <- tab * (rosum - 1) max_c <- colSums(max_oc) SA <- obs_c / max_c h <- names(SA) h[is.na(h)] <- "NA" setNames(SA, h) } # Original data dat <- data.frame(a = 1:4, b = c(2,1, 3, 4)) # Extract fixed unique levels from original data fixed_levels <- sort(unique(as.vector(dat))) # Test the updated foo function foo(dat, fixed_levels) # Updated bootstrap function boot_fun <- function(data, i, fixed_levels){ resample <- data[i, ,drop = FALSE] foo(resample, fixed_levels) } # Run Bootstrap successfully boot_result <- boot::boot(data = dat, statistic = boot_fun, R = 200, fixed_levels = fixed_levels) print(boot_result)
Why This Works
- By forcing
factor(X, levels = fixed_levels), we ensure thetabtable always has the same number of columns (matching the original data's unique values), even if a resample is missing some values. - Missing values in resamples will result in
NAin the corresponding position of theSAvector, but the length stays consistent—exactly whatbootneeds to run without errors.
内容的提问来源于stack exchange,提问作者rnorouzian
相关产品推荐
相关产品推荐

