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

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 in dat (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 boot package 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:

  1. First, define the fixed set of unique values from your original data to use as reference levels.
  2. Update foo() to accept a fixed_levels parameter, ensuring we always factorize values against this fixed set.
  3. Modify boot_fun to pass these fixed levels to foo() 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 the tab table 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 NA in the corresponding position of the SA vector, but the length stays consistent—exactly what boot needs to run without errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:32:55