【问题标题】:How to fit Generalized Additive Model with gam() where always all columns are used as predictors (no hard coding part in model fitting)如何使用 gam() 拟合广义加法模型,其中始终将所有列用作预测变量(模型拟合中没有硬编码部分)
【发布时间】:2020-11-16 09:27:13
【问题描述】:

我在R 有一个火车数据表,它总是有不同的列,例如现在数据表有以下列名称:

library(mgcv)
dt.train <- c("DE", "DEWind", "DESolar", "DEConsumption", "DETemperature", 
              "DENuclear", "DELignite")

现在我想拟合一个具有集成平滑度估计的广义加法模型 (= GAM),以预测 DE 价格。目前我将模型拟合如下:

fitModel <- mgcv::gam(DE ~ s(DEWind)+s(DESolar)+s(DEConsumption)+s(DETemperature)+
                           s(DENuclear)+s(DELignite), 
                      data = dt.train)

列名目前是硬编码的,但我不想一直更改它,我想让程序识别有多少列并将模型与现有列相匹配。所以,我想要这样的东西(适用于stats::lm()stats::glm()):

fitModel <- mgcv::gam(DE ~ .-1, data = dt.train)

很遗憾,这不适用于gam()

【问题讨论】:

    标签: datatable forecasting gam forecast columnname


    【解决方案1】:

    出于统计原因,我不建议您这样做,但是……

    nms <- c("DE", "DEWind", "DESolar", "DEConsumption", "DETemperature", 
                  "DENuclear", "DELignite")
    ## typically you'd get those names as
    ## nms <- names(dt.tain)
    
    ## identify the response
    resp <- 'DE'
    ## filter out response from `nms`
    nms <- nms[nms != resp]
    

    通过粘贴s() 位并连接由+ 分隔的字符串来创建公式的右侧:

    rhs <- paste('s(', nms, ')', sep = '', collapse = ' + ')
    

    这给了我们

    > rhs
    [1] "s(DEWind) + s(DESolar) + s(DEConsumption) + s(DETemperature) + s(DENuclear) + s(DELignite)"
    

    然后你可以添加回复和~

    fml <- paste(resp, '~', rhs, collapse = ' ')
    

    给了

    > fml
    [1] "DE ~ s(DEWind) + s(DESolar) + s(DEConsumption) + s(DETemperature) + s(DENuclear) + s(DELignite)"
    

    最后强制转换为公式对象:

    fml <- as.formula(fml)
    

    给了

    > fml
    DE ~ s(DEWind) + s(DESolar) + s(DEConsumption) + s(DETemperature) + 
        s(DENuclear) + s(DELignite)
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 2017-07-13
      • 2016-04-24
      • 2022-01-14
      • 1970-01-01
      • 2021-11-04
      • 2018-11-07
      • 2020-12-02
      相关资源
      最近更新 更多