如何从GAM模型检索残差的方差图

时间:2019-05-12 09:35:24

标签: r gam

我想检查数据中的空间自相关。 因此,我试图绘制一些GAM模型残差的方差图,但是我在网上找到的代码对我没有帮助,或者我无法使用它们。

我知道如何为原始数据绘制方差图,但无法以某种方式为模型数据(残差)绘制

这是我的代码:

library(readr)
library(mgcv)
library(ggplot2)
library(tidyverse)


dat<-read_csv("dat.csv")
View(dat)

unique(dat$parameter)
dats <- filter(dat, parameter == "esd")

model1 <- gam(value ~ s(lat, long) + s(year, k=5), data=dats)
model2 <- gam(value ~ s(lat) + s(long) + s(year, k=5), data=dats)
model3 <- gam(value ~ s(lat) + s(long) , data=dats)
model4 <- gam(value ~ s(lat) +  s(year, k=5), data=dats)
model5 <- gam(value ~ s(long) + s(year, k=5), data=dats)
AIC(model1, model2, model3, model4, model5)

summary(model1)

plot(model1, pages = 1)


### delete missing values
sum(is.na(dats))
dats2 <- na.omit(dats)
sum(is.na(dats2))

unique(dats2)
# A tibble: 249 x 8
   station parameter  value  year  temp   sal   lat  long
   <chr>   <chr>      <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 BB0001  esd        7726.  2010  18.5  6.43  55.3  14.4
 2 BB0002  esd       11338.  2010  18.3  6.55  55.4  14.5
 3 BB0003  esd       11860.  2010  18.2  6.46  55.4  14.6
 4 BB0004  esd       16961.  2010  17.9  6.37  55.4  15.1
 5 BB0005  esd       11400.  2010  18.4  6.38  55.4  15.3
 6 BB0006  esd       19815.  2010  18.7  6.48  55.4  15.4
 7 BB0007  esd        8823.  2010  18.5  5.52  55.4  16.0
 8 BB0008  esd        7761.  2010  18.2  6.25  55.5  15.6
 9 BB0009  esd        3216.  2010  18.3  6.21  55.5  16.2
10 BB0010  esd        5720.  2010  18.1  6.14  55.4  16.2
# ... with 239 more rows


var.dat <- variogram(value~1, loc= ~lat+long, data=dats2)
plot(var.dat)
## works fine

**plot(variogram(model1$residuals, robust = TRUE, data = dats2, form = ~lat))**

所以最后一部分是我遇到的麻烦。 感谢您的任何帮助!

1 个答案:

答案 0 :(得分:1)

一段时间后,我自己弄清楚了。

答案很简单。我必须先从模型中提取残差,然后才能绘制它们:

dats$resid <- residuals(model1)
var.dat_resid <- variogram(resid~1, loc= ~lat+long, data=dats)

还是谢谢!

相关问题