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

R4中predict.gam调用报错,R3可正常运行(附完整示例)

R 4.x中gam包predict函数调用报错问题及解决方法

问题现象

在R 3.6.3搭配gam包1.20版本时,predict.gam函数可正常返回结果;但升级到R 4.x搭配gam包1.22-2版本后,出现兼容性问题:

  • 执行predict(fitModel1, se.fit = TRUE, type = "response")时,抛出错误:Error in NextMethod("predict") : no method to invoke
  • 执行predict(fitModel1, se.fit = TRUE, type = "link")则完全正常。

可复现代码

library(gam)

gm1 <- predCol ~ s(VCF_nontree) + s(VCF_nonvegt) + s(VCF_treecov) + 
  s(CCI_URBAN) + s(GPW_POP)

gm2 <- predCol ~ offset(offset) + s(ACC) + s(EARS) + s(MAT) + s(PTA) + 
  s(SLP) + s(SOC) + s(TWI)

set.seed(42)
c2 <- data.frame(
  predCol = abs(rnorm(677072, 0.022, 0.03)),
  VCF_nontree = rnorm(677072, 6533, 16.3),
  VCF_nonvegt = rnorm(677072, 15.9, 12.03),
  VCF_treecov = rnorm(677072, 18.1, 18.3),
  CCI_URBAN = rnorm(677072, 0.00412, 0.013), 
  GPW_POP = rnorm(677072, 2.23, 1.28), 
  offset = rep(NA, 677072), 
  ACC = rnorm(677072, 612.6, 456.5), 
  EARS = rnorm(677072, 731.88, 291.4), 
  MAT = rnorm(677072, 22.69, 2.56), 
  PTA = rnorm(677072, 124.13, 307.9), 
  SLP = rnorm(677072, 2.41, 3.71), 
  SOC = rnorm(677072, 0.609, 0.33), 
  TWI = rnorm(677072, 118.2, 15.35)
)

fitModel1.1       <- gam::gam(gm1, data = c2, family = quasibinomial)
c2$offset         <- as.numeric(predict(fitModel1.1, type = "link"))

fitModel1         <- gam::gam(gm2, data = c2, family = quasibinomial)
# 报错的调用
# fm1               <- predict(fitModel1, se.fit = TRUE, type = "response")

解决方法

方法1:手动转换链接尺度结果到响应尺度

作为临时兼容方案,先获取链接尺度的预测值和标准误,再通过delta方法转换到响应尺度:

# 获取链接尺度的预测及标准误
fm_link <- predict(fitModel1, se.fit = TRUE, type = "link")
# 转换为响应尺度(quasibinomial族的逆链接为plogis)
fm_response <- list(
  fit = plogis(fm_link$fit),
  se.fit = fm_link$se.fit * plogis(fm_link$fit) * (1 - plogis(fm_link$fit))
)

方法2:升级gam包到最新版本

该bug已在gam包的后续版本中修复,直接更新包即可解决问题:

install.packages("gam")

更新后,原报错的predict调用可直接正常运行。


内容的提问来源于stack exchange,提问作者we need a Mat. Stat.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:21:23