-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathREADME.Rmd
218 lines (155 loc) · 6.89 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
INLAutils
==========
[![Build Status](https://travis-ci.org/timcdlucas/INLAutils.svg)](https://travis-ci.org/timcdlucas/INLAutils)
[![codecov.io](https://codecov.io/github/timcdlucas/INLAutils/coverage.svg?branch=master)](https://codecov.io/github/timcdlucas/INLAutils?branch=master)
[![cran version](http://www.r-pkg.org/badges/version/INLAutils)](https://cran.rstudio.com/web/packages/INLAutls)
A package containing utility functions for the `R-INLA` package.
There's a fair bit of overlap with [inlabru](http://www.github.com/fbachl/inlabru).
Installation
-------------
To install, first install `INLA`.
```{r installINLA, eval = FALSE}
install.packages("INLA", repos="https://www.math.ntnu.no/inla/R/stable")
```
then install `INLAutils`
```{r installINLAutils, eval = FALSE}
# From github
library(devtools)
install_github('timcdlucas/INLAutils')
# Load packages
library(INLA)
library(INLAutils)
```
```{r loadINLAutils, eval = TRUE, echo = FALSE, results = 'hide', message=FALSE, warning=FALSE}
# Now actually load the packages. This chunk is hidden
library(INLA)
library(INLAutils)
```
Overview
--------
### Plotting
I find the the `plot` function in `INLA` annoying and I like `ggplot2`.
So `INLAutils` provides an `autoplot` method for INLA objects.
```{r autoplot, eval = TRUE, echo = TRUE}
data(Epil)
##Define the model
formula = y ~ Trt + Age + V4 +
f(Ind, model="iid") + f(rand,model="iid")
result = inla(formula, family="poisson", data = Epil, control.predictor = list(compute = TRUE))
p <- autoplot(result)
```
Because these are ggplot2 objects, we can easily modify them.
```{r autoplot2, eval = TRUE, echo = TRUE}
# Find data names with names(p[[1]]$data)
p[[1]] +
geom_line(aes(colour = var), size = 1.3) +
palettetown::scale_colour_poke(pokemon = 'Oddish', spread = 4)
```
There is an autoplot method for INLA SPDE meshes.
```{r autoplot_mesh, eval = TRUE, echo = TRUE}
m = 100
points = matrix(runif(m * 2), m, 2)
mesh = inla.mesh.create.helper(
points = points,
cutoff = 0.05,
offset = c(0.1, 0.4),
max.edge = c(0.05, 0.5))
autoplot(mesh)
```
There are functions for plotting more diagnostic plots.
```{r plot_residuals, eval = TRUE, echo = TRUE}
data(Epil)
observed <- Epil[1:30, 'y']
Epil <- rbind(Epil, Epil[1:30, ])
Epil[1:30, 'y'] <- NA
## make centered covariates
formula = y ~ Trt + Age + V4 +
f(Ind, model="iid") + f(rand,model="iid")
result = inla(formula, family="poisson", data = Epil,
control.predictor = list(compute = TRUE, link = 1))
ggplot_inla_residuals(result, observed, binwidth = 0.1)
ggplot_inla_residuals2(result, observed, se = FALSE)
```
Finally there is a function for combining shapefiles, rasters (or INLA projections) and meshes.
For more fine grained control the geoms defined in [inlabru](http://www.github.com/fbachl/inlabru) might be useful.
```{r shapefileraster,eval = TRUE, echo = TRUE, message = FALSE}
# Create inla projector
n <- 20
loc <- matrix(runif(n*2), n, 2)
mesh <- inla.mesh.create(loc, refine=list(max.edge=0.05))
projector <- inla.mesh.projector(mesh)
field <- cos(mesh$loc[,1]*2*pi*3)*sin(mesh$loc[,2]*2*pi*7)
projection <- inla.mesh.project(projector, field)
# And a shape file
crds <- loc[chull(loc), ]
SPls <- SpatialPolygons(list(Polygons(list(Polygon(crds)), ID = 'a')))
# plot
ggplot_projection_shapefile(projection, projector, SPls, mesh)
```
### Analysis
There are some helper functions for general analyses.
`INLAstep` runs stepwise variable selection with INLA.
```{r INLAstep, eval = TRUE, echo = TRUE, message = FALSE}
data(Epil)
stack <- inla.stack(data = list(y = Epil$y),
A = list(1),
effects = list(data.frame(Intercept = 1, Epil[3:5])))
result <- INLAstep(fam1 = "poisson",
Epil,
in_stack = stack,
invariant = "0 + Intercept",
direction = 'backwards',
include = 3:5,
y = 'y',
y2 = 'y',
powerl = 1,
inter = 1,
thresh = 2)
result$best_formula
autoplot(result$best_model, which = 1)
```
`makeGAM` helps create a function object for fitting GAMs with INLA.
```{r GAM, eval = TRUE, echo = TRUE}
data(Epil)
formula <- makeGAM('Age', invariant = '', linear = c('Age', 'Trt', 'V4'), returnstring = FALSE)
formula
result = inla(formula, family="poisson", data = Epil)
```
### Spatial leave-one-out cross-validation (sloo-cv)
The package `INLAutils` provides an approach to run sloo-cv for INLA objects.
```{r inlasloo, eval = TRUE, echo = TRUE, results = 'hide', message = FALSE}
# generate a dataframe and INLA output for the function
set.seed(10)
coords <- data.frame(long = c(rnorm(70), rnorm(30, 3)), lat = rnorm(100))
x <- data.frame(x1 = rnorm(100), x2 = rnorm(100))# x1 no relat., x2 pos. relat.
y <- x$x2 * 2 + rnorm(100)
dataf1 <- sp::SpatialPointsDataFrame(coords = coords, data = data.frame(y = y, x))
mesh <- INLA::inla.mesh.2d(loc = sp::coordinates(dataf1), max.edge = c(3, 3),cutoff = 1.3)
spde <- INLA::inla.spde2.matern(mesh, alpha=2)#SPDE model is defined
A <- INLA::inla.spde.make.A(mesh, loc = sp::coordinates(dataf1))#projector matrix
dataframe <- data.frame(dataf1) #generate dataframe with response and covariate
modform<-stats::as.formula(paste('y ~ -1+ x1 + x2 + y.intercept + f(spatial.field, model=spde)'))
stk <- INLA::inla.stack(data = list(y=dataframe$y),
A = list(A, 1),
effects = list(list(spatial.field=1:spde$n.spde),
list(y.intercept = rep(1, length(dataframe$y)),
covariate = dataframe[c(-1)])),
tag='est')
out <- INLA::inla(modform, family='normal',Ntrials = 1, data=INLA::inla.stack.data(stk, spde=spde),
control.predictor = list(A =INLA::inla.stack.A(stk),link=1),
control.compute = list( config=TRUE),control.inla = list(int.strategy='eb'))
out.field <- INLA::inla.spde2.result(out,'spatial.field', spde, do.transf = TRUE)
range.out <- INLA::inla.emarginal(function(x) x, out.field$marginals.range.nominal[[1]])
# parameters for the SLOO process
ss <- 20 # sample size to process (number of SLOO runs)
rad <- min(range.out, max(dist(coords)) / 4) # define the radius of the spatial buffer surrounding the removed point. Make sure it isn't bigger than 25% of the study area (Le Rest 2014)
modform <- y ~ -1+ y.intercept + x1 + x2 + f(spatial.field, model=spde)
alpha <- 0.05 # rmse and mae confidence intervals (1-alpha)
# run the function
cv <- inlasloo(dataframe = dataframe,
long = 'long', lat = 'lat',
y = 'y', ss = ss,
rad = rad, modform = modform,
mesh = mesh, family = 'normal',
mae = TRUE)
```