【问题标题】:How to run a loop inside a loop for a gam object如何在 gam 对象的循环内运行循环
【发布时间】:2019-02-03 11:51:08
【问题描述】:

我试图在多重插补后预测新的观察结果。 newdata 和要使用的模型都是列表对象。该方法的正确性不是问题,而是如何在多重插补后使用预测函数我们有一个新数据,它是一个列表。下面是我的代码。

library(betareg)
library(mice)
library(mgcv)
data(GasolineYield)
dat1 <- GasolineYield

dat1 <- GasolineYield
dat1$yield <- with(dat1,
ifelse(yield > 0.40 | yield < 0.17,NA,yield)) # created missing values

datim <- mice(dat1,m=30) #imputing missing values
mod1 <- with(datim,gam(yield ~ batch + emp,family=betar(link="logit"))) #fit models using gam

创建用于预测的数据集

datnew <- complete(datim,"long")
datsplit <- split(datnew,datnew$.imp)

下面的代码只是在没有新数据的情况下测试了预测。我观察到的问题是 tp 保存为 1 x 32 矩阵而不是 30 x 32 矩阵。但是打印选项打印出 30 x 32 但我无法保存它。

tot <- 0
for(i in 1:30){
tot <- mod1$analyses[[i]]
tp <- predict.gam(tot,type = "response")
print(tp)
}

下面的代码是我尝试使用 newdata 预测新的观察结果。在这里我只是迷路了,我不知道该怎么做。

datnew <- complete(datim,"long")
datsplit <- split(datnew,datnew$.imp)
tot <- 0
for(i in 1:30){
tot <- mod1$analyses[[i]]
tp <- predict.gam(tot,newdata=datsplit[[i]], type = "response")
print(tp)
}

有人可以帮助我了解如何最好地去做吗?

【问题讨论】:

  • 你使用什么包?显示library() 电话。我不会在模型函数周围使用 with() - 这就是 data 参数的用途。需要注意的是,确保datsplit 的每个组件都包含原始模型中使用的所有变量。
  • 我正在使用以下库:mice、mgcv 和 betareg。 with 函数是为每个插补数据集运行模型
  • 你不需要with();这就是 gam()data 参数的用途。

标签: r gam


【解决方案1】:

我终于找到解决问题了。这是解决方案:

datnew <- complete(datim,"long")# stack all the imputation data

虽然我必须指出这应该是你的新数据集

我假设在构建模型时不使用它。我打开这个#thread 的目的是解决如何在多重插补/使用使用多重插补数据集构建的模型后使用新数据预测观察结果的问题。

datsplit <- split(datnew,datnew$.imp)
tot <- list()
tot_ <- list()
for(i in 1:30){
for(j in 1:30){
tot[[j]] <- predict.gam(mod1$analyses[[i]],newdata=datsplit[[j]])
}
tot_[[i]] <- tot
}
# flatten the lists within lists
totfl <- tot_ %>% flatten()
#nrow is the number of observations to be predicted as contained in the 
#newdata set (datsplit)
totn <- matrix(unlist(totfl),nrow=32) 
apply(totn,1,mean) #takes the means of prediction across the 30 data set

我希望这对有类似问题的人有所帮助。我曾经遇到过一个关于如何在多重插补后预测新数据的问题,我想这将回答该线程中包含的一些问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多