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

gamlasso中使用offset项触发下标错误的技术求助

问题:gamlasso添加offset项时触发错误

问题复现

使用gamlasso生成变量平滑估计功能正常,但加入offset项后报错,复现代码如下:

构建线性项模型矩阵

# 线性项的模型矩阵
gamlasso_data$X <- model.matrix(~ as.factor(time) + age_0,
                                data = gamlasso_data)[,-1]   # -1 移除默认截距列

gamlasso模型代码(注释offset时正常运行)

# 公式法 - 年龄/时间模型
gamlassofit = gamlasso(count ~ X +
        #                      population_est + 
                               s(age, time, bs='fs'),
                       family = 'poisson',
                       data = gamlasso_data,
                       num.knots = -1,
                       seed = 1,
        #              offset = log(gamlasso_data$population_est),
                       num.iter = 10) 

取消注释offset参数后触发错误:

Must extract column with a single valid subscript.
x Subscript var has the wrong type double.
i It must be numeric or character.

对比:普通GAM模型添加offset正常运行

fitted_gam <- gam(count ~ s(age, time, bs='fs'),
                  data = gamlasso_data,
                  family = poisson,
                  offset = log(population_est),
                  method = "REML")

解决方法

根据错误提示,gamlasso的offset参数对输入格式的要求和gam不同,可尝试以下两种方案:

  1. 将offset写入模型公式
    把offset项直接整合到模型公式中,删除单独的offset参数:

    gamlassofit = gamlasso(count ~ X + s(age, time, bs='fs') + offset(log(population_est)),
                           family = 'poisson',
                           data = gamlasso_data,
                           num.knots = -1,
                           seed = 1,
                           num.iter = 10)
    
  2. 提前生成offset列并传入列名
    先将计算后的offset值作为新列加入数据集,再给offset参数传入列名(字符或数值型下标):

    # 提前计算offset列
    gamlasso_data$log_pop <- log(gamlasso_data$population_est)
    
    # 调用gamlasso时传入列名
    gamlassofit = gamlasso(count ~ X + s(age, time, bs='fs'),
                           family = 'poisson',
                           data = gamlasso_data,
                           num.knots = -1,
                           seed = 1,
                           offset = "log_pop", # 或用列的数值下标,比如如果是第5列就写5
                           num.iter = 10)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:01:18