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

使用nptest包中np.boot函数报错:不允许缺失值与NaN

非参数自举(Non-parametric Bootstrapping)报错解决

问题重现

执行以下R代码时触发错误及大量警告:

library(nptest)

set.seed(1000)

bootstrap_primary_premium=np.boot(Primary,statistic=mean, R=500)

print(bootstrap_primary_premium)

错误信息:

Error in quantile.default(bootdist[, j], probs = probs) :
missing values and NaN's not allowed if 'na.rm' is FALSE
In addition: There were 50 or more warnings (use warnings() to see the first 50)

问题原因

你的Primary数据中存在缺失值(NA/NaN),默认情况下mean()函数不会忽略缺失值,导致每次自举样本计算均值时产生NaN,最终在计算分位数时触发错误,同时累积大量警告。

解决方案

方案1:在统计量中忽略缺失值

修改statistic参数,传入带na.rm=TRUE的均值函数,让计算均值时自动跳过缺失值:

library(nptest)

set.seed(1000)

# 自定义统计量函数,加入na.rm=TRUE
bootstrap_primary_premium <- np.boot(Primary, 
                                     statistic = function(x) mean(x, na.rm = TRUE), 
                                     R = 500)

print(bootstrap_primary_premium)

方案2:先清理数据中的缺失值

提前移除Primary中的缺失值,再进行自举操作:

library(nptest)

set.seed(1000)

# 清理缺失值
Primary_clean <- na.omit(Primary)

bootstrap_primary_premium <- np.boot(Primary_clean, 
                                     statistic = mean, 
                                     R = 500)

print(bootstrap_primary_premium)

补充说明

  • 可以先用sum(is.na(Primary))查看数据中缺失值的数量,判断哪种方案更合适:如果缺失值占比极低,清理数据影响不大;如果缺失值占比高,建议用方案1保留更多样本信息。
  • 处理缺失值后,警告信息会自动消失,因为自举样本中不会再产生NaN。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:45:06