R语言 无法将数据放入MetaGAM

sirbozc5  于 2023-06-27  发布在  其他
关注(0)|答案(2)|浏览(97)

我尝试使用方法described in this vignette通过metaGAM运行模拟数据,但每次尝试将GAM模型传递到metagam时都会出现奇怪的错误。以下是模拟数据和拟合:

#### Libraries ####
library(tidyverse)
library(mgcv)
library(metagam)
set.seed(1)

#### Sim Data ####
n <- 100
x <- seq(0, 1, length.out = n)
fx1 <- sin(2 * pi * x)
fx2 <- sin(3 * pi * x)
fx3 <- sin(2.4 * pi * x)
y1 <- fx1 + rnorm(n, sd = 0.5)
y2 <- fx2 + rnorm(n, sd = .3)
y3 <- fx3 + rnorm(n, sd = .4)

#### Plot ####
par(mfrow=c(1,3))
plot(x, y1, main = "Simulated Data 1")  
lines(x, fx1, lwd = 2) 
plot(x, y2, main = "Simulated Data 2")
lines(x, fx2, lwd = 2) 
plot(x, y3, main = "Simulated Data 3") 
lines(x, fx3, lwd = 2) 

#### Assign to Dataframe ####
df <- data.frame(x,y1,y2,y3) %>% 
  as_tibble()
df

#### Fit Data ####
fit1 <- gam(y1 ~ s(x), data = df)
fit2 <- gam(y2 ~ s(x), data = df)
fit3 <- gam(y3 ~ s(x), data = df)

#### Combine ####
models <- list(cohort1 = fit1, 
               cohort2 = fit2,
               cohort3 = fit3)

当我尝试使用main命令运行它时:

#### Fit into MetaGAM ####
metafit <- metagam(models, 
                   terms = "s(x)")

它只是给了我这个错误,我假设这意味着它无法找到我的模型中的样条项或数据:

Error in FUN(X[[i]], ...) : Unknown term  requested

我运行models来检查是否不包含s(x),但输出似乎表明它编码正确:

$cohort1

Family: gaussian 
Link function: identity 

Formula:
y1 ~ s(x)

Estimated degrees of freedom:
4.77  total = 5.77 

GCV score: 0.2317925     

$cohort2

Family: gaussian 
Link function: identity 

Formula:
y2 ~ s(x)

Estimated degrees of freedom:
6.64  total = 7.64 

GCV score: 0.1065703     

$cohort3

Family: gaussian 
Link function: identity 

Formula:
y3 ~ s(x)

Estimated degrees of freedom:
5.37  total = 6.37 

GCV score: 0.1722314

修改样条以显式地包括基础项(例如,s(x, bs = "cr)对于CR样条)似乎没有帮助。我该怎么解决?

ojsjcaue

ojsjcaue1#

不支持对metagams默认预测类型“iterms”使用平滑器:
请注意,不支持type=“terms”,因为它可能导致平滑项的估计零标准差。
(from ?metagam
因此,您需要指定另一种预测类型(“响应”或“链接”)。例如:

metafit <- metagam(models, 
                   terms = "s(x)",
                   type = "response"
                   )

但是,这可能不是你想要的?

xurqigkl

xurqigkl2#

我想明白了由于某些原因,这个包要求您在通过metagam运行GAMs之前 * 始终 * 使用strip_rawdata函数。在拟合每个GAM时,似乎也不能使用默认的样条线,因此我将基础更改为bs="cr"。通过使用以下代码立即修复了该问题:

#### Fit Data ####
fit1 <- gam(y1 ~ s(x, bs = "cr"), data = df)
fit2 <- gam(y2 ~ s(x, bs = "cr"), data = df)
fit3 <- gam(y3 ~ s(x, bs = "cr"), data = df) # changes each basis

#### Combine ####
models <- list(cohort1 = strip_rawdata(fit1), 
               cohort2 = strip_rawdata(fit2),
               cohort3 = strip_rawdata(fit3)) # strips data

#### Fit and Plot ####
fit <- metagam(models)
plot(fit) # plots fit

这就是我想要的

相关问题