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

R语言非参数Bootstrap函数报错:替换项数量与长度不匹配

Bootstrap计算连续数据众数时报错的解决方法

问题重现

编写了用于计算连续数据众数的my.mode函数,以及基于boot包执行非参数bootstrap的non.p.bootstrap函数:

my.mode <- function(vector) {
    hist <-hist(vector, breaks = length(vector), plot = FALSE)
    densest <- max(hist$density)
    mode <- hist$mid[hist$density == densest]
    return(mode)
}

non.p.bootstrap <- function(vector, n) {
    mode.stat <- function(my.data,i) return(my.mode(my.data[i]))
    b <- boot(data = vector, statistic = mode.stat, R = n)
    return(b)
}

在1000个数据点的向量上运行时,触发报错:

错误于t.star[r, ] <- res[[r]] : 要替换的项数不是替换长度的倍数

报错原因

boot包要求统计量函数(即mode.stat调用的my.mode)每次返回的结果长度必须固定不变。但当前my.mode中,当直方图存在多个区间的密度同时达到最大值时,hist$mid[hist$density == densest]会返回多个中点值,导致不同bootstrap样本返回的结果长度不一致,进而触发上述错误。

修复方案

确保my.mode始终返回单个值,可选择以下两种方式之一:

方式1:取第一个候选众数

修改my.mode,当存在多个密度峰值时,返回第一个峰值对应的中点:

my.mode <- function(vector) {
    hist <- hist(vector, breaks = length(vector), plot = FALSE)
    densest <- max(hist$density)
    mode_candidates <- hist$mid[hist$density == densest]
    # 取第一个候选众数
    return(mode_candidates[1])
}

方式2:取候选众数的平均值

如果希望结果更稳健,可返回所有候选众数的平均值:

my.mode <- function(vector) {
    hist <- hist(vector, breaks = length(vector), plot = FALSE)
    densest <- max(hist$density)
    mode_candidates <- hist$mid[hist$density == densest]
    # 取候选众数的平均值
    return(mean(mode_candidates))
}

测试验证

使用修改后的函数运行测试:

set.seed(123)
test_data <- rnorm(1000)
bootstrap_result <- non.p.bootstrap(test_data, 1000)
print(bootstrap_result)

此时bootstrap过程可正常执行,返回boot函数的标准输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:01:09