首页 > 解决方案 > 如何在 gam 对象的循环内运行循环

问题描述

我试图在多重插补后预测新的观察结果。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)
}

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

标签: rgam

解决方案


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

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

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


推荐阅读