mgcv:如何在 predict.gam 中使用“排除"参数? [英] mgcv: How to use 'exclude' argument in predict.gam?

查看:65
本文介绍了mgcv:如何在 predict.gam 中使用“排除"参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的模型,我想在忽略随机效应的同时提取预测值.如?predict.gam此处所述,我正在使用 exclude 参数,但出现错误.我的错误在哪里?

I have a model structured as follows, and I would like to extract the predicted values while ignoring the random effect. As specified in ?predict.gam and here, I am using the exclude argument, but I am getting an error. Where is my mistake?

dt <- data.frame(n1 = runif(500, min=0, max=1),
             n2 = rep(1:10,50), 
             n3 = runif(500, min=0, max=2),
             n4 = runif(500, min=0, max=2),
             c1 = factor(rep(c("X","Y"),250)),
             c2 = factor(rep(c("a", "b", "c", "d", "e"), 100)))

mod = gam(n1 ~ 
           s(n2, n3, n4, by=c1) +
           s(c2, bs="re"),
         data=dt)

newd=data.table(expand.grid(n1=seq(min(dt$n1), max(dt$n1), 0.5), 
                        n2=1:10,
                        n3=seq(min(dt$n3), max(dt$n3), 0.5),
                        n4=seq(min(dt$n4), max(dt$n4), 0.5),
                        c1=c("X", "Y")))
newd$pred <- predict.gam(mod, newd, exclude = "s(c2)")

In predict.gam(mod, newd, exclude = "s(c2)"): not all required variables have been supplied in  newdata! 

推荐答案

exclude 与您假设的方式不同.您仍然需要在 newd 中为 predict.gam 提供所有变量.请参阅我的此答案,了解 predict.gam 背后的内容.

exclude does not work in the way as you assumed. You still need to provide all variables in your newd for predict.gam. See my this answer for what is behind predict.gam.

这是您需要做的:

## pad newd with an arbitrary value for variable c2
newd$c2 <- "a"
## termwise prediction
pt <- predict.gam(mod, newd, type = "terms", exclude = "s(c2)")
## linear predictor without random effect
lp_no_c2 <- rowSums(pt) + attr(pt, "constant")

这篇关于mgcv:如何在 predict.gam 中使用“排除"参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆