-
Notifications
You must be signed in to change notification settings - Fork 1
/
README.Rmd
286 lines (196 loc) · 10 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
---
output: github_document
---
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "README-"
)
```
# rakeR
[![Build Status](https://travis-ci.org/philmikejones/rakeR.svg?branch=master)](https://travis-ci.org/philmikejones/rakeR)
[![codecov](https://codecov.io/gh/philmikejones/rakeR/branch/master/graph/badge.svg)](https://codecov.io/gh/philmikejones/rakeR)
[![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/rakeR)](https://cran.r-project.org/package=rakeR)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.821506.svg)](https://doi.org/10.5281/zenodo.821506)
[![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)
Create a spatial microsimulated data set in R using iterative proportional
fitting ('raking').
## Install
Install the latest stable version from CRAN:
```{r install-cran, eval=FALSE, include=TRUE}
install.packages("rakeR")
```
Or install the development version with `devtools`:
```{r install-rakeR, eval=FALSE, include=TRUE}
# Obtain devtools if you don't already have it installed
# install.packages("devtools")
# Install rakeR development version from GitHub
devtools::install_github("philmikejones/rakeR")
```
Load the package with:
```{r load-rakeR}
library("rakeR")
```
## Overview
`rakeR` has three main functions.
The first stage is always to use `rk_weight()` to produce a matrix of fractional weights.
This matrix stores weights for each individual in each zone.
From this weight matrix, `rakeR` has functions to create fractional weights (`rk_extract()`) or integerised cases (`rk_integerise()`), depending on your needs and use cases.
Fractional (`rk_extract()`ed) weights are generally more accurate, while integer cases are probably the most intuitive to use and are useful as inputs
for further modeling.
To create fractional weights use `rk_weight()` then `rk_extract()`, and to produce integerised weights use `rk_weight()` then `rk_integerise()`.
## Inputs
To perform the weighting you should supply two data frames.
One data frame should contain the constraint information (`cons`) with counts per category for each zone (e.g. census counts).
The other data frame should contain the individual--level data (`inds`), i.e. one row per individual.
In addition, it is necessary to supply a character vector with the names of the constraint variables in `inds` (`vars`).
This is so that `rakeR` knows which are the contraint variables and which variables it should be simulating as an output.
Below are examples of `cons`, `inds`, and `vars`.
```{r data}
cons <- data.frame(
"zone" = letters[1:3],
"age_0_49" = c(8, 2, 7),
"age_gt_50" = c(4, 8, 4),
"sex_f" = c(6, 6, 8),
"sex_m" = c(6, 4, 3),
stringsAsFactors = FALSE
)
inds <- data.frame(
"id" = LETTERS[1:5],
"age" = c("age_gt_50", "age_gt_50", "age_0_49", "age_gt_50", "age_0_49"),
"sex" = c("sex_m", "sex_m", "sex_m", "sex_f", "sex_f"),
"income" = c(2868, 2474, 2231, 3152, 2473)
)
vars <- c("age", "sex")
```
It is _essential_ that the unique levels in the constraint variables in the
`inds` data set match the variables names in the `cons` data set.
For example, `age_0_49` and `age_gt_50` are variable names in `cons` and the unique levels of the `age` variable in `inds` precisely match these:
```{r labels-test}
all.equal(
levels(inds$age), colnames(cons[, 2:3]) # cons[, 1] is the id column
)
```
Without this, the functions do not know how to match the `inds` and `cons` data
and will fail so as not to return spurious results.
## `rk_weight()`
(Re-)weighting is done with `rk_weight()` which returns a data frame of raw weights.
```{r weight}
weights <- rk_weight(cons = cons, inds = inds, vars = vars)
weights
```
The raw weights tell you how frequently each individual (`A`-`E`) should appear
in each zone (`a`-`c`).
The raw weights are useful when validating and checking performance of the
model, so it can be necessary to save these separately.
They aren't very useful for analysis however, so we can `rk_extract()` or `rk_integerise()` them into a useable form.
## `rk_extract()`
`rk_extract()` produces aggregated totals of the simulated data for each category in each zone.
`rk_extract()`ed data is generally more accurate than `rk_integerise()`d data, although the user should be careful this isn't spurious precision based on context and knowledge of the domain.
Because `rk_extract()` creates a column for each level of each variable, numerical variables (e.g. income) must be removed or `cut()` (otherwise the result would include a new column for each unique numerical value):
```{r extract}
inds$income <- cut(inds$income, breaks = 2, include.lowest = TRUE,
labels = c("low", "high"))
ext_weights <- rk_extract(weights, inds = inds, id = "id")
ext_weights
```
`rk_extract()` returns one row per zone, and the total of each category (for
example female and male, or high and low income) will match the known
population.
## `rk_integerise()`
The `rk_integerise()` function produces a simulated data frame populated with simulated individuals.
This is typically useful when:
* You need to include numerical variables, such as income in the example.
* You want individual cases to use as input to a dynamic or agent-based model.
* You want 'case studies' to illustrate characteristics of individuals in an
area.
* Individual-level data is more intuitive to work with.
```{r integerise}
int_weights <- rk_integerise(weights, inds = inds)
int_weights[1:6, ]
```
`rk_integerise()` returns one row per case, and the number of rows will match
the known population (taken from `cons`).
## `rk_rake()`
`rk_rake()` is a wrapper for `rk_weight() %>% rk_extract()` or
`rk_weight() %>% rk_integerise()`.
This is useful if the raw weights (from `rk_weight()`) are not required.
The desired output is specified with the `output` argument, which can be
specified with `"fraction"` (the default) or `"integer"`.
The function takes the following arguments in all cases:
* `cons`
* `inds`
* `vars`
* `output` (default `"fraction"`)
* `iterations` (default 10)
Additional arguments are required depending on the output requested.
For `output = "fraction"`:
* `id`
For `output = "integer"`:
* `method` (default `"trs"`)
* `seed` (default 42)
Details of these context-specific arguments can be found in the
respective documentation for `rk_integerise()` or `rk_extract()`.
```{r rake-int-exaple}
rake_int <- rk_rake(cons, inds, vars, output = "integer",
method = "trs", seed = 42)
rake_int[1:6, ]
```
```{r rake-frac-example}
rake_frac <- rk_rake(cons, inds, vars, output = "fraction", id = "id")
rake_frac
```
## Contributing
Please note that this project is released with a [Contributor Code of Conduct](CONDUCT.md).
By participating in this project you agree to abide by its terms.
## Issues and feedback
Feedback on the API,
[bug reports/issues](https://github.com/philmikejones/rakeR/issues),
and pull requests are very welcome.
## Acknowledgements
Many of the functions in this package are based on code written by
[Robin Lovelace](https://github.com/Robinlovelace) and
[Morgane Dumont](https://github.com/modumont) for their book
[*Spatial Microsimulation with R* (2016), Chapman and Hall/CRC Press](https://www.crcpress.com/Spatial-Microsimulation-with-R/Lovelace-Dumont/p/book/9781498711548).
Their book is an excellent resource for learning
about spatial microsimulation and understanding what's going on under the hood
of this package.
The book and code are licensed under the terms below:
Copyright (c) 2014 Robin Lovelace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The [rewighting (ipfp) algorithm](https://github.com/awblocker/ipfp) is
written by Andrew Blocker.
The [`wrswoR` package](http://krlmlr.github.io/wrswoR/) used for fast sampling
without replacement is written by Kirill Müller.
Thanks to [Tom Broomhead](http://mhs.group.shef.ac.uk/members/tom-broomhead/)
for his feedback on error handling and suggestions on function naming, to [Andrew Smith](https://github.com/virgesmith) for bug fixes, and Derrick Atherton for suggestions, feedback, and testing.
Data used in some of the examples and tests ('cakeMap') are anonymised data from the [Adult Dental Health Survey](https://data.gov.uk/dataset/adult_dental_health_survey), used under terms of the [Open Government Licence](http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/).
## Contact
philmikejones at gmail dot com
## License
Copyright 2016-18 Phil Mike Jones.
rakeR is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
rakeR is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with rakeR. If not, see <http://www.gnu.org/licenses/>.