-
Notifications
You must be signed in to change notification settings - Fork 8
/
classstructure.Rmd
626 lines (395 loc) · 19.2 KB
/
classstructure.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
---
title: "Classes in `hpiR`"
author: "Andy Krause"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{hpiR Classes}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, collapse=TRUE, messages=FALSE, eval=FALSE)
```
## Introduction
This vignette explains the various classes of objects and data used in the `hpiR` package. By executing the code in this vignette you can create examples of all classes of objects used in the `hpiR` package.
## Class Structures
The table below shows the basic information on the various **S3** classes used in the package. The naming convention of classes is such that prefixes indicate the domain (or the type) of the information contained in the object. The major domains are:
<br>
* **"series"** = objects referring to information relevant to the entire hpi series (a set of hpi collections)
* **"hpi"** = objects referring to information relevant to the entire hpi collection
* **"index"** = objects referring to information relevant only to the index itself
* **"rt"** or **"hed"** = objects with information specific to a particular index approach (**"rt"** for repeat transaction and **"hed"** for hedonic model)^[Additional approaches will be added here in the future.]
* Suffixes of these classes currently include **"data"** and **"model"**
* **"plot"** = objects containing plot objects.
The `hpi` collection object is the "core" unit of the `hpiR` package. The object will contain all the information, temporary objects (data, models, etc.) and analysis about a single house price index.
The `serieshpi` object is a "super-unit" that contains multiple house price indexes within it. Indexes within a series share the same data, modeling approach and parameters; they differ only in the length of the indexes. Additionally there are two types of analyses that can only be applied to series: forecast accuracy (`calcForecastError()`) and revision (`calcRevision()`). Also note that in an `serieshpi` object the data objects are moved out of the `hpi` objects and into the `serieshpi` object to avoid duplication of data storage.
The table below shows the various classes of objects used with `hpiR`, their type, what they inherit from, what function creates them and a short description. A tilde (**~**) in front of the inherits value signifies that some of the components of the object inherit from that class, but not all.
<br>
| Type | Class | Inherits | Created by | Description |
| :---- | :----- | :------: | :-----: | :-------------------------------------- |
| **Super** | | | | |
| | `serieshpi` | *many* | `createSeries()` | A series of progressively longer indexes
||||||
| **Core** | | | | |
| | `hpi` | *many* | `**Index()` wrappers | Unified house price index collection object containing data, model and index as well as additional analytics that can be added to it
| | `hpiaccuracy` | `data.frame` | `calcAccuracy()` | Accuracy of the index |
||||||
| **Data** | | | | |
| | `hpidata` | `data.frame` | `dateToPeriod()` | Transaction data.frame with dates converted to relative periods |
| | `rtdata` | `hpidata`, `data.frame` | `rtCreateTrans()` | Data.frame of repeat transactions with standardized field names |
| | `heddata` | `hpidata`, `data.frame` | `hedCreatTrans()` | Data.frame of transactions with some standardized field names for use in hedonic model approach |
||||||
| **Model** | | | | |
| | `hpimodel` | Many (ex. `lm`, `rlm`) | `hpiModel()` | Flexible list of model results |
| | `rtmodel` | Many (ex. `lm`, `rlm`) | `rtModel()` | List of repeat transaction model results |
| | `hedmodel` | Many (ex. `lm`, `rlm`) | `hedModel()` | List of hedonic model results |
||||||
| **Index** | | | | |
||||||
| | `hpiindex` | ~`ts` | `modelToIndex()` | List of index information. `$index` slot is a `ts` object |
| | `indexsmooth` | `ts` | `smoothIndex()` | Smoothed index |
| | `indexvolatility` | NONE | `calcVolatility()` | List of rolling, mean and median index volatility |
||||||
| **Series** | | | | |
| | `seriesrevision` | NONE | `calcRevision()` | List of the period, mean and median revision |
| | `seriesaccuracy` | `hpiaccuracy`, `data.frame` | `calcSeriesAccuracy()` | Accuracy of the series |
||||||
| **Visualization** | | | | |
| | `plotindex` | `gg`, `ggplot` | `plot.hpiindex()`, `plot.hpi` | Plotting object for an index |
| | `plotseries` | `gg`, `ggplot` | `plot.serieshpi()` | Plotting object for an index series |
| | `plotrevision` | `gg`, `ggplot` | `plot.seriesrevision()` | Plotting object for revision statistics |
| | `plotaccuracy` | `gtable`, `gTree`, `grob`, `gDesc` | `plot.hpiaccuracy()`, `plot.seriesaccuracy` | Plotting object for accuracy results |
| | `plotvolatility` | `gg`, `ggplot` | `plot.indexvolatility()` | Plotting object for index volatility |
## Examples And Explanation
Small examples of any of the classes in the table above are available in the `hpiR` package as pre-loaded data. Use `data(ex_'name of class')` to access. Ex: `data(ex_hpidata)`.
### Loading
Begin by loading the `hpiR` package. It is assumed that you've followed the instructions in the **"introduction"** vignette in order to obtain the package.
```{r silent_library_load, echo=FALSE}
suppressMessages(suppressWarnings(library(hpiR)))
suppressMessages(suppressWarnings(library(knitr)))
suppressMessages(suppressWarnings(library(magrittr)))
```
```{r hpir_load}
library(hpiR)
```
Next, load the example dataset of Seattle house transactions into your R session. We'll limit to just the central city (**area** equal to 13, 14, and 15). This can also be accessed via `data(ex_sales)`.
```{r data_load}
# Load all sales
data(seattle_sales)
# Create a smaller sample of sales
ex_sales <- seattle_sales %>%
dplyr::filter(., area %in% c(13, 14, 15))
# Or just load it
data(ex_sales)
```
### Data
#### 'hpidata' objects
`hpidata` objects inherit from `data.frame`, but are very flexible and the collection of fields that may be in these objects is solely dependent on the data being used. The only requirements for creating an `hpidata` object is that there must be an R formatted **date** field that can be turned into a period field.
The `dateToPeriod()` function will create an `hpidata` object by converting the date into a period. The only difference between the `hpidata` object and the original data.frame is the addition of **trans_date** and **trans_period** columns and the **periodicity**, **min_date**, **max_date** and **period_table** attributes.
```{r create_hpidata}
ex_hpidata <- dateToPeriod(trans_df = ex_sales,
date = 'sale_date',
periodicity = 'monthly')
```
```{r class_hpidata}
class(ex_hpidata)
```
```{r str_hpidata}
str(ex_hpidata)
```
#### Approach-based data objects
Each of the index creation approaches (currently just **rt** and **hed**) will have their own data object classes that include the necessary fields and structures for these approach types. The name format here is "xxdata"", where 'xx' is the approach abbreviation.
The `rtdata` object holds repeat transactions and contains the eight standard fields shown below as well as the **period_table** attribute.
```{r create_rtdata}
ex_rtdata <- rtCreateTrans(trans_df = ex_hpidata,
prop_id = 'pinx',
trans_id = 'sale_id',
price = 'sale_price')
```
```{r class_rtdata}
class(ex_rtdata)
```
```{r str_rtdata}
str(ex_rtdata)
```
The `heddata` object requires no changes from the original `hpidata` object and looks the same, with the exception of field standardization (**pinx** is now **prop_id**, **sale_id** is now **trans_id**, **sale_price** is now **price**, **sale_date** is now **date**. )
```{r create_heddata}
ex_heddata <- hedCreateTrans(trans_df = ex_sales,
prop_id = 'pinx',
trans_id = 'sale_id',
price = 'sale_price',
date = 'sale_date',
periodicity = 'monthly')
```
```{r class_heddata}
class(ex_heddata)
```
```{r str_heddata}
str(ex_heddata)
```
### Modeling
Results from modeling the data prior to creating indexes is stored in `hpimodel` objects. These objects contain eight standard slots, shown below. The slots are standardized across approaches, with the exception of the `model_obj` slot which will contain an object that is specific to the approach being used to estimate the index.
```{r create_timematrix, echo=FALSE, eval=FALSE}
# Created for internal purposes, not shown in Vignette
ex_timematrix <- rtTimeMatrix(ex_rtdata)
```
```{r create_hpimodel}
ex_hpimodel <- hpiModel(model_type = 'rt',
hpi_df = ex_rtdata,
estimator = 'base',
log_dep = TRUE)
```
```{r class_hpimodel}
class(ex_hpimodel)
```
```{r str_hpimodel}
str(ex_hpimodel, max.level=1)
```
Below we see an example of a `model_obj` from a repeat transactions model. This is very similar to what you'd get from a call to a linear model (`lm(...)`)
```{r create_model_obj}
ex_rtmodel <- ex_hpimodel$model_obj
```
```{r class_model_obj}
class(ex_rtmodel)
```
```{r str_model_obj}
str(ex_rtmodel, max.level=1, give.attr=FALSE)
```
We also show an example of a `model_obj` from a hedonic price method, again similar to an `lm(...)` output.
```{r create_hmodel_obj}
ex_hedmodel <- hpiModel(model_type = 'hed',
hpi_df = ex_heddata,
estimator = 'base',
dep_var = 'price',
ind_var = c('tot_sf', 'beds', 'baths'),
log_dep = TRUE)[["model_obj"]]
```
```{r class_hmodel_obj}
class(ex_hedmodel)
```
```{r str_hmodel_obj}
str(ex_hedmodel, max.level=1, give.attr=FALSE)
```
### Indexes and Smoothing
The `modelToIndex()` function will take an `hpimodel` object and turn it into an `hpiindex` object. `hpiindex` objects contain five standard slots.
```{r create_hpiindex}
ex_hpiindex <- modelToIndex(model_obj = ex_hpimodel)
```
```{r class_hpiindex}
class(ex_hpiindex)
```
```{r str_hpiindex}
str(ex_hpiindex, max.level=1)
```
If we want to add a smoothed index to this object, we use the `smoothIndex()` function. In its default state, this function just return a simple `ts` (time-series) object of the smoothed index.
```{r create_smoothindex}
ex_smoothindex <- smoothIndex(ex_hpiindex)
```
```{r class_smoothindex}
class(ex_smoothindex)
```
```{r str_smoothindex}
str(ex_smoothindex)
```
To add it directly to the `hpiindex` object, we add the **"in_place = TRUE"** argument which will add it to the **\$smooth** slot in the `hpiindex` object. Note that the class of **temp_index** stays the same (`hpiindex`), only the **\$smooth** slot is added with an object of class `smoothindex` (inheriting from `ts`).
```{r smooth_inplace}
temp_index <- smoothIndex(ex_hpiindex, in_place = TRUE)
```
```{r class_smooth_inplace}
class(temp_index)
```
```{r class_smooth_inplaces}
class(temp_index$smooth)
```
```{r str_smooth_inplace}
str(temp_index)
```
If you want to store plots of `hpiindex` objects, they are returned as `plotindex` objects, inheriting from `gg` and `ggplot` (from the `ggplot2` package)
```{r create_plotindex}
ex_plotindex <- plot(ex_hpiindex)
```
```{r class_plotindex}
class(ex_plotindex)
```
### Wrapper
The index level wrappers (`rtIndex()` and `hedIndex()` -- more to come) combine the above steps -- data prep, modeling and index creation -- into a single function, the output of which is an hpi collection, or simply, an `hpi` object. Directly after creation with a wrapper this object is a list of:
1. A data object (`hpidata`)
2. A model object (`hpimodel`)
3. An index object (`hpiindex`)
```{r create_hpi}
ex_hpi <- rtIndex(trans_df = ex_rtdata,
estimator = 'robust',
log_dep = TRUE,
trim_model = TRUE,
smooth = TRUE)
```
```{r class_hpi}
class(ex_hpi)
```
```{r str_hpi}
str(ex_hpi, max.level=1)
```
### Analyzing Indexes
#### Volatility
Index volatility can be calculated by providing an `hpiindex` object to the `calcVolatility()` function. The result is an object of class `indexvolatility`, containing three vector objects as well as two attributes indicating the original index and the window used.
```{r create_indexvolatility}
ex_indexvolatility <- calcVolatility(index = ex_hpiindex,
window = 5)
```
```{r class_indexvolatility}
class(ex_indexvolatility)
```
```{r str_indexvolatility}
str(ex_indexvolatility)
```
The `indexvolatility` object can be nested within an `hpiindex` object by setting **in_place = TRUE**.
```{r vol_inplace}
temp_index <- calcVolatility(index = ex_hpiindex,
window = 3,
in_place = TRUE)
```
```{r class_volinplace1}
class(temp_index)
```
```{r class_volinplace2}
class(temp_index$volatility)
```
```{r str_volinplace}
str(temp_index, max.level=1, give.attr=FALSE)
```
Volatility plots can be saved in objects of class `plotvolatility`, inheriting from `gg` and `ggplot`
```{r create_volplot}
ex_plotvolatility <- plot(ex_indexvolatility)
```
```{r class_volplot}
class(ex_plotvolatility)
```
#### Accuracy (Fitting)
Calculating an index's (fitting) accuracy through either **insample** or **kfold** (out of sample) methods via `calcAccuracy()` returns an object of class `hpiaccuracy`, inheriting from `data.frame`. These object contain four fields, shown below. In `hpiaccuracy` objects, each observation is that is being tested for accuracy is only found once. This differs from the `seriesaccuracy` objects which are discussed later in which an observation may be tested against an index for each index in the series and therefore may appear multiple times in the `seriesaccuracy` object.
```{r create_hpiaccr}
ex_hpiaccuracy <- calcAccuracy(hpi_obj = ex_hpi,
test_type = 'rt',
test_method = 'insample')
```
```{r class_hpiaccr}
class(ex_hpiaccuracy)
```
```{r str_hpiaccr}
str(ex_hpiaccuracy)
```
`hpiaccuracy` objects can be added directly to an `hpi` object with the **in_place = TRUE** argument.^[Accuracy results are added to `hpi` objects and not `hpindex` object because they require data that is outside of the `hpiindex` object and therefore relate to the hpi collection more than just the index.]
```{r hpia_inplace}
temp_hpi <- calcAccuracy(hpi_obj = ex_hpi,
test_type = 'rt',
test_method = 'insample',
in_place = TRUE)
```
```{r class_hpia_inplace1}
class(temp_hpi)
```
```{r class_hpia_inplace2}
class(temp_hpi$accuracy)
```
```{r str_hpia_inplace}
str(temp_hpi, max.level=1, give.attr=FALSE)
```
An `hpiaccuracy` object can be plotted and saved to a `plotaccuracy` object, but need the `return_plot=TRUE` argument to return to an object.
```{r create_plotaccr, fig.keep='none'}
ex_plotaccuracy <- plot(ex_hpiaccuracy, return_plot = TRUE)
```
```{r class_plotaccr}
class(ex_plotaccuracy)
```
#### Series
A series of `hpi` objects are created with `createSeries()`. This results in a `serieshpi` object, with two initial slots: **\$data** (`hpidata` object) and **\$hpis** a list of `hpi` objects (minus the data component which has been removed to avoid duplication.)
```{r create_serieshpi}
ex_serieshpi <- createSeries(hpi_obj = ex_hpi,
train_period = 48,
max_period = 60)
```
```{r class_serieshpi}
class(ex_serieshpi)
```
```{r str_serieshpi}
str(ex_serieshpi, max.level=1)
```
Series can be plotted and saved into a `plotseries` object.
```{r create_plotserieshpi}
ex_plotseries <- plot(ex_serieshpi)
```
```{r class_plotserieshpi}
class(ex_plotseries)
```
#### Revision
The revision of a series is calculated with `calcRevision()` and returns an object of class `seriesrevision`. This object contains a `data.frame` of revision by period and median and mean summaries of overall revision levels.
```{r create_seriesrevision}
ex_seriesrevision <- calcRevision(series_obj = ex_serieshpi)
```
```{r class_seriesrevision}
class(ex_seriesrevision)
```
```{r str_seriesrevision}
str(ex_seriesrevision)
```
To add the revision to the `serieshpi` object, use **in_place = TRUE**.
```{r srev_inplace}
temp_series <- calcRevision(series_obj = ex_serieshpi,
in_place = TRUE)
```
```{r class_srev_inplace1}
class(temp_series)
```
```{r class_srev_inplace2}
class(temp_series$revision)
```
```{r str_srev_inplace}
str(temp_series, max.level=1)
```
Plotting revisions can be saved to a `plotrevision` object.
```{r create_plotrevision}
ex_plotrevision <- plot(ex_seriesrevision)
```
```{r class_plotrevision}
class(ex_plotrevision)
```
### Series Accuracy
Finally, accuracy can be calculated at the series level by providing a `serieshpi` object to `calcSeriesAccuracy()`, resulting in a `seriesaccuracy` object. `seriesaccuracy` objects look nearly identical to `hpiaccuracy` objects, however they differ in two respects: 1) they may include estimate of accuracy for the same observation multiple times ^[This will **not** happen only when using a test_method of type "forecast" and a "forecast_length" of 1.]; 2) they will have a **series** field, indicating from which index in the series the accuracy estimate is derived.
Using **test_method = 'forecast'** will create a true, prediction-type test of accuracy (out of sample and into the future), where **kfold** is out of sample (but with knowledge of the future) and **insample** is just a simple fitting measure.
```{r create_seriesaccr}
ex_seriesaccuracy <- calcSeriesAccuracy(series_obj = ex_serieshpi,
test_method = 'insample',
test_type = 'rt')
```
```{r class_seriesaccr}
class(ex_seriesaccuracy)
```
```{r str_seriesaccr}
str(ex_seriesaccuracy)
```
This object can be added directly to the `serieshpi` object by using the **in_place = TRUE** argument.
```{r create_sainplace}
temp_series <- calcSeriesAccuracy(series_obj = ex_serieshpi,
test_method = 'insample',
test_type = 'rt',
in_place=TRUE)
```
```{r class_sainplace}
class(temp_series)
```
```{r class_sainplace2}
class(temp_series$accuracy)
```
```{r str_sainplace}
str(temp_series, max.level=1)
```
Finally, `seriesaccuracy` objects can be saved to a plot of class `plotaccuracy`
```{r create_plotsaccuracy, fig.keep='none'}
ex_plotaccuracy <- plot(ex_seriesaccuracy, return_plot = TRUE)
```
```{r class_plotsaccuracy}
class(ex_plotaccuracy)
```
For more information on using the above functions please see the **"Introduction"** Vignette also provided with this package.