-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatasets.Rmd
1666 lines (1403 loc) · 81.7 KB
/
datasets.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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Datasets / Données"
output:
html_document:
code_folding: show
#toc: TRUE
---
<br>
<br>
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = F, echo = TRUE, results = "hide", message = FALSE, tidy = T)
```
## Canadian Parliamentarians and Census Data, 1991-2015
Note: I did this work as part of my doctoral dissertation and I am currently using the dataset in a working paper. Here's how to cite the data when using it in your own work: Vallée-Dubois, Florence. (2020). Canadian Parliamentarians and Census Data, 1991-2015 [data file].
Censuses of Canada are carried out every five years. Since 1991, the census data is available at the level of federal electoral districts, so it is possible to match these data with information on parliamentarians (i.e, info on who has been elected in each riding). The end product looks like this, with observations for every MP, with info their riding at the time of their election.
{width=1000px}
Here, I share with you the code I used to get there. It required dealing text data (the ridings' name), and a lot of back-and-forth between the code and output. I welcome comments on how to improve this code!
The end-product can be found [here](https://github.com/florencevdubois/florencevdubois.github.io/tree/master/documentation/data/output) in .csv format. The following variables are included:
- `name`: MP's name
- `birth`: MP's date of birth
- `gender`: MP's gender
- `pid`: MP's party affiliation
- `riding_start_date`: start date for the parliamentary term
- `riding_end_date`: end date for the parliamentary term
- `dist_name`: riding's name
- `year`: year used to match census info with parliamentarians' info (in general, they're the start year for the parliament, except in the 34th parliament, when 1991 is used instead of 1988)
- `dist_nb`: riding's number
- `0` to `100`: age categories -- number of people in each age
### Some context
Because most elections since 1991 happened between census years (1993-1997-2000-2004-2006-2008-2011-2015), I interpolated population data in-between census years in order to obtain values on the demogrpahic profile of ridings on election years. As of now, I focused on the population's age, but I will extend this work to other demographic variables that are available at the level of federal ridings (e.g., the unemployment rate, the number of immigrants, etc.).
But before we start matching the censuses with parliamentary data, we need to address one important challenge: representation orders have changed since the early 1990s. In other words, there has been redistricting.
- The 1993 election used the 1987 representation order. There were 295 seats in the House of Commons.
- The 1997 and 2000 elections used the 1996 representation order. There were 301 seats in the House.
- The 2004, 2006, 2008 and 2011 elections used the 2003 representation order. There were 308 seats in the House.
- The 2015 election used the 2013 representation order. There are now 338 seats in the House.
Census data are available for the representation orders that come before and after each census. For example, the 1996 census data are provided for the 1987 and 1996 representation orders. This is useful, because we can use different pairs of censuses to interpolate demographics in different election years. For example, the 2000 election was run under the _1996 r.o._ and falls between the 1996 and 2001 censuses. We will use the _1996 and 2001 censuses at the level of the 1996 r.o._ to find the demographic profile in 2000. In the same way, we will match the 1996 election data with the _1996 census data_ under the _1987 r.o._, because this was the representation order in the 1996 election.
I used the following resources to learn about federal electoral districts, representation orders, and census and parliamentary data in general:
- [Federal electoral districts codes](https://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index338&lang=e)
- [Election Modelling by Byron Weber Becker](http://election-modelling.ca/rawdata/bycandidate/)
- [Legal measures governing changes in federal electoral districts](https://lop.parl.ca/sites/ParlInfo/default/en_CA/legislation/legalMeasuresDistricts)
- [History of the Federal Electoral Ridings, 1867-2010](https://open.canada.ca/data/en/dataset/ea8f2c37-90b6-4fee-857e-984d3060184e)
- [Canada - Elections](https://guides.lib.uwo.ca/canadaelections)
- [Federal electoral district (FED)](https://www12.statcan.gc.ca/census-recensement/2011/ref/dict/geo025-eng.cfm)
- [(Archive 2003-2013) Canada's Federal Electoral Districts](https://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index&lang=e)
- [RO 2013](https://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index338&lang=e)
- [RO 2003](https://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index&lang=e#list)
- [Boundaries](https://open.canada.ca/data/en/dataset?q=%22Federal+Electoral+Districts+of+Canada%22&collection=geogratis&sort=&page=1)
In what follows, we will:
1) Recode each census dataset. In some instances, we will need to recode the same census twice, under two different representation orders (this is the case in 1996, 2001 and 2011).
2) Merge censuses together by representation order.
3) Interpolate demographic values for election years that fall in-between census years.
4) Clean-up the parliamentary data, which contain info on MPs elected in the House, their riding, party, gender, etc.
5) Finally, we will merge the (interpolated) demographics data with the parliamentary data.
There is a LOT of code so I recommend hiding all code (you can use the button at the top of this page), then showing one chunk at a time as you read this post. You will need these packages to follow along:
```{r}
library(tidyverse)
library(lubridate)
library(fuzzyjoin) # i'm not even sure I ended up using it, but made a few attempts with this package.
```
### 1) Recoding Censuses by Representation Order
I found the raw census datasets on the [Statistics Canada wesbsite](https://www12.statcan.gc.ca/datasets/index-eng.cfm?Temporal=2016). Selecting "Federal electoral district" under the "Geography" tab, you will see which census data products are available at the level of ridings. For now, I got the "Age and sex" topic and downloaded every census file available. The older files are available in a weird format (Beyond 20/20). Beyond 20/20 is a software available on Windows. I am a Mac user, but I opened the files on a Windows machine, then saved them in .csv. If you don't want to go through the hassle, I've made the .csv files available in the [Github repo](https://github.com/florencevdubois/florencevdubois.github.io) for this website.
I will not be walking you through each dataset recode because the steps are always the same. But basically, we start by reshaping the data from wide to long in order to get an observation for each riding/age combination (for e.g. Rosemont 0 yr old, Rosemont 1 yr old, Rosemont 2yrs old, etc.) This tells us how many people of every age are in each riding. Then, we clean-up the names of ridings (remove special characters, etc.) This is where I had to do the most back-and-forth, because some censuses used different spellings for the same riding (double dashes instead of single dashes, for e.g.), so in the end I needed to correct some spellings manually. It's a good thing I had some knowledge about Canadian federal elections ;)
#### 1991 census (1987 Representation order)
```{r 1991_1987 recode}
d91 <- read.csv("documentation/data/input/1991census_1987order.csv", sep = ",")
d91_clean <- d91 %>%
rename(geo = Géographie, # choosing more basic variable names
sex = Sexe..3.) %>%
filter(str_detect(geo, "[:alpha:]"), # keeping observations with names (without are census subdivisions)
str_detect(sex, "Total"), # keeping total values for sex -- we don't need men and women
!str_detect(geo, "Newfoundland | Terre-Neuve"), # removing obs that are the provinces
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick | Nouveau-Brunswick"),
!str_detect(geo, "Quebec | Québec"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "British Columbia | Colombie-Britannique"),
!str_detect(geo, "Yukon Territory"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada \\(00\\)")) %>% # removing the Canada obs
gather(age, value, Total...Groupes.d.âge:X90.et.plus) %>% # from wide to long
filter(!str_detect(age, "Total")) %>% # removing obs that are "age group totals"
mutate(age = str_remove(age, "X")) %>% # removing "X" in front of age categories
dplyr::select(geo, age, value) # keeping the 3 variables of interest
# we now have a value (obs.) for each electoral district and age category
# just looking through the age variable to check what's remaining
table(d91_clean$age)
# people <1 y.o. are identified as "less than one year" and people >90 y.o.
# are categorized as "more than 90"
d91_clean <- d91_clean %>%
mutate(age = ifelse(age == "Moins.de.1", 0, age), # recoding these two
age = ifelse(age == "90.et.plus", 90, age)) %>% # "< 1 year" = "0" and "> 90" = "90"
filter(!str_detect(age, "\\.")) # age categories with periods in them correspond to age groups
# we don't want them, we only want single ages (except for the 90+ age group)
table(d91_clean$age) # seems pretty good
class(d91_clean$age) # I have a feeling this variable is not numeric
d91_clean <- d91_clean %>%
mutate(age = as.numeric(age)) # transforming it to numeric
table(d91_clean$age)
class(d91_clean$age)
d91_clean <- d91_clean %>%
mutate(census = 1991, # adding a variable telling us which census it is
ro = 1987) # adding a variable for the R.O. (I removed it later, turns out I did not need it)
# Here's an important step. The "geo" variable has the names of district _and_ their numbers
# (in parentheses). I want to keep these two pieces of information, but in two different
# variables, because I may need one of the other for merging purposes later on. I will
# therefore split this variable into two (dist_name and dist_nb), then clean them up
# (especially district names).
d91_clean <- d91_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"), # removing digits from geo to create "dist_name"
dist_name = str_remove_all(dist_name, "\\(\\)"), # removing the empty parentheses
# there is still information in parentheses (the district names' translation), we want to
# get rid of that
dist_name = str_remove_all(dist_name, "\\([^()]+\\)"),
# creating the "dist_nb" variable by extracting what's in parentheses from the "geo" variable
# (I could not only extract digits because there are other digits, which have nothing to do
#with the district numbers)
dist_nb = str_extract_all(geo, "\\([^()]+\\)")) %>%
unnest(dist_nb) %>% # separating the information we extracted from parentheses
filter(str_detect(dist_nb, "-", negate = TRUE),
# remove obs where the district nb is not only a number
str_detect(dist_nb, "[:alpha:]", negate = TRUE)) %>%
# again, extract digits from their parenteses
mutate(dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
# I don't think the next line and the next are necessary in 1991, but in other years it is
unnest(dist_nb) %>%
filter(str_detect(dist_nb, " ", negate = TRUE)) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
# the next lines make sure that district names have the same spelling in every census recode
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"), # this could probably be more tidy
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
# Timiskaming is called Timiskaming French River in the 1996 census (first back-and-forth!)
dist_name = ifelse(dist_name == "Timiskaming", "Timiskaming-French River", dist_name)) %>%
select(-geo, -ro) # we want every data frames to have the same variables
length(unique(d91_clean$dist_nb)) # just making sure we have 295 seats
length(unique(d91_clean$dist_name)) # all good
```
Most of the work is now done, but we have to pay attention to at least one thing when recoding other censuses: other raw datasets are not always organized the same way. Statistics Canada did not only change the data formats, they also changed the names of variables, how district names and number are compiled, etc. So we won't always to able to run _exactly_ the same code --- a few changes will be necessary here and there.
#### 1996 census (1987 Representation order)
```{r 1996_1987 recode}
d96 <- read.csv("documentation/data/input/1996census_1987order.csv", sep = ",")
d96_clean <- d96 %>%
rename(geo = Géographie,
sex = Sexe..3.) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick | Nouveau-Brunswick"),
!str_detect(geo, "Quebec | Québec"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "British Columbia | Colombie-Britannique"),
!str_detect(geo, "Yukon Territory"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada \\(00\\)")) %>%
gather(age, value, Total...Âge:X90.) %>%
filter(!str_detect(age, "Total")) %>%
mutate(age = str_remove(age, "X")) %>%
dplyr::select(geo, age, value)
table(d96_clean$age)
d96_clean <- d96_clean %>%
mutate(age = ifelse(age == "moins.de.1", 0, age),
age = ifelse(age == "90.", 90, age)) %>%
filter(!str_detect(age, "\\."))
table(d96_clean$age)
class(d96_clean$age)
d96_clean <- d96_clean %>%
mutate(age = as.numeric(age))
table(d96_clean$age)
class(d96_clean$age)
d96_clean <- d96_clean %>%
mutate(census = 1996,
ro = 1987)
d96_clean <- d96_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_name = str_remove_all(dist_name, "\\([^()]+\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)")) %>%
unnest(dist_nb) %>%
filter(str_detect(dist_nb, "-", negate = TRUE),
str_detect(dist_nb, "[:alpha:]", negate = TRUE)) %>%
mutate(dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
filter(str_detect(dist_nb, " ", negate = TRUE)) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both")) %>%
select(-geo,-ro)
length(unique(d96_clean$dist_nb))
length(unique(d96_clean$dist_name))
```
#### 1996 census (1996 Representation order)
```{r 1996_1996 recode}
d96_2 <- read.csv("documentation/data/input/1996census_1996order.csv", sep = ",")
d96_2_clean <- d96_2 %>%
rename(geo = Géographie,
sex = Sexe..3.) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick | Nouveau-Brunswick"),
!str_detect(geo, "Quebec | Québec"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "British Columbia | Colombie-Britannique"),
!str_detect(geo, "Yukon Territory"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada \\(00\\)")) %>%
gather(age, value, Total...Âge:X90.) %>%
filter(!str_detect(age, "Total")) %>%
mutate(age = str_remove(age, "X")) %>%
dplyr::select(geo, age, value)
table(d96_2_clean$age)
d96_2_clean <- d96_2_clean %>%
mutate(age = ifelse(age == "moins.de.1", 0, age),
age = ifelse(age == "90.", 90, age)) %>%
filter(!str_detect(age, "\\."))
table(d96_2_clean$age)
class(d96_2_clean$age)
d96_2_clean <- d96_2_clean %>%
mutate(age = as.numeric(age))
table(d96_2_clean$age)
class(d96_2_clean$age)
d96_2_clean <- d96_2_clean %>%
mutate(census = 1996,
ro = 1996)
d96_2_clean <- d96_2_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)"),
dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/")) %>%
select(-geo, -ro)
length(unique(d96_2_clean$dist_nb))
length(unique(d96_2_clean$dist_name))
```
#### 2001 census (1996 Representation order)
```{r 2001_1996 recode}
d01 <- read.csv("documentation/data/input/2001census_1996order.csv", encoding = "latin1")
summary(d01)
d01_clean <- d01 %>%
rename(geo = Géographie,
sex = `Sexe..3.`) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick - Nouveau-Brunswick \\(13\\)"),
!str_detect(geo, "Québec \\(24\\)"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "British Columbia | Colombie-Britannique"),
!str_detect(geo, "Yukon Territory"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada"),
!str_detect(geo, "Nunavut \\(62\\)")) %>%
gather(age, value, `Total...Âge`:`X100.`) %>%
filter(!str_detect(age, "Total")) %>%
dplyr::select(geo, age, value)
table(d01_clean$age)
d01_clean <- d01_clean %>%
mutate(age = ifelse(age == "Moins.de.1.an", 0, age),
age = ifelse(age == "X100.", 100, age),
age = str_remove_all(age, "X")) %>%
filter(!str_detect(age, "\\."))
table(d01_clean$age)
class(d01_clean$age)
d01_clean <- d01_clean %>%
mutate(age = as.numeric(age))
table(d01_clean$age)
class(d01_clean$age)
d01_clean <- d01_clean %>%
mutate(census = 2001,
ro = 1996)
d01_clean <- d01_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)"),
dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/")) %>%
select(-geo, -ro)
length(unique(d01_clean$dist_nb))
length(unique(d01_clean$dist_name))
```
#### 2001 census (2003 Representation order)
```{r 2001_2003 recode}
d01_2 <- read.csv("documentation/data/input/2001census_2003order.csv", encoding = "latin1")
summary(d01_2)
d01_2_clean <- d01_2 %>%
rename(geo = Géographie,
sex = `Sexe..3.`) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick - Nouveau-Brunswick \\(13\\)"),
!str_detect(geo, "Québec \\(24\\)"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "British Columbia | Colombie-Britannique"),
!str_detect(geo, "Yukon Territory"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada"),
!str_detect(geo, "Nunavut \\(62\\)")) %>%
gather(age, value, `Total...Âge`:`X100.`) %>%
filter(!str_detect(age, "Total")) %>%
dplyr::select(geo, age, value)
table(d01_2_clean$age)
d01_2_clean <- d01_2_clean %>%
mutate(age = ifelse(age == "Moins.de.1.an", 0, age),
age = ifelse(age == "X100.", 100, age)) %>%
mutate(age = str_remove(age, "ans"),
age = str_remove(age, "an")) %>%
filter(!str_detect(age, "\\.1"),
!str_detect(age, "\\.2"),
!str_detect(age, "\\.3"),
!str_detect(age, "\\.4"),
!str_detect(age, "\\.5"),
!str_detect(age, "\\.6"),
!str_detect(age, "\\.7"),
!str_detect(age, "\\.8"),
!str_detect(age, "\\.9")) %>%
mutate(age = str_remove(age, "X"),
age = str_remove(age, "\\."))
table(d01_2_clean$age)
class(d01_2_clean$age)
d01_2_clean <- d01_2_clean %>%
mutate(age = as.numeric(age))
table(d01_2_clean$age)
class(d01_2_clean$age)
d01_2_clean <- d01_2_clean %>%
mutate(census = 2001,
ro = 2003)
d01_2_clean <- d01_2_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)"),
dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "/"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/")) %>%
select(-geo, -ro)
length(unique(d01_2_clean$dist_nb))
length(unique(d01_2_clean$dist_name))
```
#### 2006 census (2003 Representation order)
```{r 2006_2003 recode}
d06 <- read.csv("documentation/data/input/2006census_2003order.csv", encoding = "latin1")
summary(d06)
d06_clean <- d06 %>%
rename(geo = Géographie,
sex = `Sexe..3.`) %>%
select(-`Âge.médian`) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick / Nouveau-Brunswick \\(13\\)"),
!str_detect(geo, "Québec \\(24\\)"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "Colombie-Britannique \\(59\\)"),
!str_detect(geo, "Yukon Territory"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada"),
!str_detect(geo, "Nunavut \\(62\\)")) %>%
gather(age, value, `Total...Âge`:`X100.ans.et.plus`) %>%
filter(!str_detect(age, "Total")) %>%
dplyr::select(geo, age, value)
table(d06_clean$age)
d06_clean <- d06_clean %>%
mutate(age = ifelse(age == "Moins.de.1.an", 0, age),
age = ifelse(age == "X100.ans.et.plus", 100, age),
age = str_remove_all(age, "X")) %>%
filter(!str_detect(age, "ans"))
table(d06_clean$age)
class(d06_clean$age)
d06_clean <- d06_clean %>%
mutate(age = as.numeric(age))
table(d06_clean$age)
class(d06_clean$age)
d06_clean <- d06_clean %>%
mutate(census = 2006,
ro = 2003)
d06_clean <- d06_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)"),
dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/")) %>%
select(-geo, -ro)
length(unique(d06_clean$dist_nb))
length(unique(d06_clean$dist_name))
```
#### 2011 census (2003 Representation order)
```{r 2011_2003 recode}
d11 <- read.csv("documentation/data/input/2011census_2003order.csv", encoding = "latin1")
summary(d11)
d11_clean <- d11 %>%
rename(geo = Géographie,
sex = `Sexe..3.`) %>%
select(-`Âge.médian`) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick / Nouveau-Brunswick \\(13\\)"),
!str_detect(geo, "Quebec | Québec"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "Colombie-Britannique \\(59\\)"),
!str_detect(geo, "Yukon \\(60\\)"),
!str_detect(geo, "Northwest Territories"),
!str_detect(geo, "Canada"),
!str_detect(geo, "Nunavut \\(62\\)")) %>%
gather(age, value, `Total...Âge`:`X100.ans.et.plus`) %>%
filter(!str_detect(age, "Total")) %>%
dplyr::select(geo, age, value)
table(d11_clean$age)
d11_clean <- d11_clean %>%
mutate(age = ifelse(age == "Moins.de.1.an", 0, age),
age = ifelse(age == "X100.ans.et.plus", 100, age),
age = str_remove(age, "X")) %>%
filter(!str_detect(age, "ans"))
table(d11_clean$age)
class(d11_clean$age)
d11_clean <- d11_clean %>%
mutate(age = as.numeric(age))
table(d11_clean$age)
class(d11_clean$age)
d11_clean <- d11_clean %>%
mutate(census = 2011,
ro = 2003)
d11_clean <- d11_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)"),
dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/")) %>%
select(-geo, -ro)
length(unique(d06_clean$dist_nb))
length(unique(d06_clean$dist_name))
```
#### 2011 census (2013 Representation order)
```{r 2011_2013 recode}
d11_2 <- read.csv("documentation/data/input/2011census_2013order.csv", encoding = "latin1")
summary(d11_2)
d11_2_clean <- d11_2 %>%
rename(geo = Géographie,
sex = `Sexe..3.`) %>%
select(-`Âge.médian`) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick / Nouveau-Brunswick \\(13\\)"),
!str_detect(geo, "Quebec | Québec"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan \\(47\\)"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "Colombie-Britannique \\(59\\)"),
!str_detect(geo, "Yukon \\(60\\)"),
!str_detect(geo, "Northwest Territories / Territoires du Nord-Ouest \\(61\\)"),
!str_detect(geo, "Canada"),
!str_detect(geo, "Nunavut \\(62\\)")) %>%
gather(age, value, `Total...Âge`:`X100.ans.et.plus`) %>%
filter(!str_detect(age, "Total")) %>%
dplyr::select(geo, age, value)
table(d11_2_clean$age)
d11_2_clean <- d11_2_clean %>%
mutate(age = ifelse(age == "Moins.de.1.an", 0, age),
age = ifelse(age == "X100.ans.et.plus", 100, age),
age = str_remove(age, "X")) %>%
filter(!str_detect(age, "ans"))
table(d11_2_clean$age)
class(d11_2_clean$age)
d11_2_clean <- d11_2_clean %>%
mutate(age = as.numeric(age))
table(d11_2_clean$age)
class(d11_2_clean$age)
d11_2_clean <- d11_2_clean %>%
mutate(census = 2011,
ro = 2013)
d11_2_clean <- d11_2_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)"),
dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/")) %>%
select(-geo, -ro)
length(unique(d11_2_clean$dist_nb))
length(unique(d11_2_clean$dist_name))
```
#### 2016 census (2013 Representation order)
```{r 2016_2013 recode}
d16 <- read.csv("documentation/data/input/2016census_2013order.csv", encoding = "latin1")
summary(d16)
d16_clean <- d16 %>%
rename(geo = Géographie,
sex = `Sexe..3.`) %>%
select(-`Âge.moyen`) %>%
filter(str_detect(geo, "[:alpha:]"),
str_detect(sex, "Total"),
!str_detect(geo, "Newfoundland | Terre-Neuve"),
!str_detect(geo, "Prince Edward Island | Île-du-Prince-Édouard"),
!str_detect(geo, "Nova Scotia | Nouvelle-Écosse"),
!str_detect(geo, "New Brunswick / Nouveau-Brunswick \\(13\\)"),
!str_detect(geo, "Quebec | Québec"),
!str_detect(geo, "Ontario \\(35\\)"),
!str_detect(geo, "Saskatchewan \\(47\\)"),
!str_detect(geo, "Manitoba"),
!str_detect(geo, "Alberta"),
!str_detect(geo, "Colombie-Britannique \\(59\\)"),
!str_detect(geo, "Yukon \\(60\\)"),
!str_detect(geo, "Northwest Territories / Territoires du Nord-Ouest \\(61\\)"),
!str_detect(geo, "Canada"),
!str_detect(geo, "Nunavut \\(62\\)")) %>%
gather(age, value, `Total...Âge`:`X100.ans.et.plus`) %>%
filter(!str_detect(age, "Total")) %>%
dplyr::select(geo, age, value)
table(d16_clean$age)
d16_clean <- d16_clean %>%
mutate(age = ifelse(age == "Moins.de.1.an", 0, age),
age = ifelse(age == "X100.ans.et.plus", 100, age),
age = str_remove(age, "X")) %>%
filter(!str_detect(age, "ans"))
table(d16_clean$age)
class(d16_clean$age)
d16_clean <- d16_clean %>%
mutate(age = as.numeric(age))
table(d16_clean$age)
class(d16_clean$age)
d16_clean <- d16_clean %>%
mutate(census = 2016,
ro = 2013)
d16_clean <- d16_clean %>%
mutate(dist_name = str_remove_all(geo, "[0-9]+"),
dist_name = str_remove_all(dist_name, "\\(.*\\)"),
dist_nb = str_extract_all(geo, "\\([^()]+\\)")) %>%
unnest(dist_nb) %>%
filter(str_detect(dist_nb, "%", negate = TRUE)) %>%
mutate(dist_nb = str_extract_all(dist_nb, "(?<=\\().+?(?=\\))")) %>%
unnest(dist_nb) %>%
mutate(dist_name = str_replace_all(dist_name, " - ", "-"),
dist_name = str_replace_all(dist_name, " -", "-"),
dist_name = str_replace_all(dist_name, "- ", "-"),
dist_name = str_replace_all(dist_name, "--", "-"),
dist_name = str_trim(dist_name, side = "both"),
dist_name = str_replace_all(dist_name, " / ", "/"),
dist_name = str_replace_all(dist_name, " /", "/")) %>%
select(-geo, -ro)
length(unique(d16_clean$dist_name))
length(unique(d16_clean$dist_nb))
```
### 2) Merging Censuses Together by Representation Order
Here, we will merge censuses that use the same representation orders. For example, we need to merge the 1991 and 1996 census that use both the 1987 r.o. in order to be able (later) to interpolate age breakdowns in 1993, an election that was run under the 1987 r.o. At this step, there were (yet again) some spelling differences in district names. This made my head want to explode, but I managed to reach the expected result !
#### Merge 1991 census (1987 Representation order) with 1996 census (1987 Representation order) to map with _1993 parliament data._
```{r match ro1987}
# we want to have one observation per electoral district, with variables for each age category
d91_clean <- d91_clean %>%
spread(age, value)
d96_clean <- d96_clean %>%
spread(age, value)
# we then bind the 2 dataframes (vertically, one on top of the other)
ro1987 <- rbind(d91_clean, d96_clean) %>%
gather(age, value, `0`:`90`) %>% # again, we gather the age variables
# now we have one observation for each district-census-age combination (long format)
spread(census, value) # finally, we come back to a wide format
length(unique(ro1987$dist_nb)) # making sure we have 295 seats
length(unique(ro1987$dist_name))
check <- ro1987 %>% # making sure the 2 census years are complete
filter(is.na(`1991`) == TRUE |
is.na(`1996`) == TRUE) # all good
```
#### Merge 1996 census (1996 Representation order) with 2001 census (1996 Representation order) to map with _1997 parliament data_ and _2000 parliament data._
```{r match ro1996}
d96_2_clean <- d96_2_clean %>%
spread(age, value)
# I have to merge 90+ yo categories because previous censuses do not have 90-100 y.o.
# it creates problems when binding
d01_clean <- d01_clean %>%
spread(age, value) %>%
unnest(dist_nb) %>% # dist_nb was a list
dplyr::group_by(dist_nb) %>%
mutate(`90+` = `90` + `91` + `92` +`93` +`94` +`95` +`96` +`97` +`98` +`99` +`100`) %>% # making a sum of values in the 90-100 age categories
ungroup() %>%
select(-`90`, -`91`, -`92`, -`93`, -`94`,
-`95`, -`96`, -`97`, -`98`, -`99`, -`100`) %>% # removing the extra variables
rename(`90` = `90+`) # ok, all set
ro1996 <- rbind(d96_2_clean, d01_clean) %>%
gather(age, value, `0`:`90`) %>%
spread(census, value)
length(unique(ro1996$dist_nb))
check <- ro1996 %>%
filter(is.na(`1996`) == TRUE |
is.na(`2001`) == TRUE)
# Nunavut is 61001 in 1996 and 62001 in 2001. Merging them.
ro1996 <- ro1996 %>%
gather(year, value, `1996`:`2001`) %>%
spread(age, value) %>%
mutate(dist_nb = ifelse(dist_nb == "62001" & year == "2001", "61001", dist_nb)) %>%
drop_na() %>%
gather(age, value, `0`:`90`) %>%
spread(year, value)
check <- ro1996 %>%
filter(is.na(`1996`) == TRUE |
is.na(`2001`) == TRUE)
list <- check %>% distinct(dist_name, dist_nb) # we have a problem, let's check the district names
# Fix different spellings
ro1996 <- ro1996 %>%
gather(year, value, `1996`:`2001`) %>%
unnest(dist_nb) %>%
drop_na() %>%
dplyr::group_by(dist_nb, age) %>%
mutate(new_name = dist_name[year == 1996]) %>% # making sure all districts use the 1996 names -- StatCan changed some names even though the r.o. did not change, but it does not mean that the districts changed (they have the same number). This is going to cause some trouble later, but we will fix it.
dplyr::ungroup() %>%
mutate(dist_name = new_name) %>%
select(-new_name) %>%
spread(year, value)
check <- ro1996 %>%
filter(is.na(`1996`) == TRUE |
is.na(`2001`) == TRUE)
length(unique(ro1996$dist_name))
length(unique(ro1996$dist_nb)) # all set
```
#### Merge 2001 census (2003 Representation order) with 2006 census (2003 Representation order) to map with _2004 parliament data._
```{r match ro2003}
d01_2_clean <- d01_2_clean %>%
spread(age, value)
d06_clean <- d06_clean %>%
spread(age, value)
ro2003 <- rbind(d01_2_clean, d06_clean) %>%
gather(age, value, `0`:`100`) %>%
spread(census, value)
ro2003 <- ro2003 %>%
gather(year, value, `2001`:`2006`) %>%
drop_na() %>%
dplyr::group_by(dist_nb, age) %>%
mutate(new_name = dist_name[year == 2001]) %>% # recode districts with different names in 2001 and 2006
dplyr::ungroup() %>%
mutate(dist_name = new_name) %>%
select(-new_name) %>%
spread(year, value)
length(unique(ro2003$dist_nb))
length(unique(ro2003$dist_name))
check <- ro2003 %>%
filter(is.na(`2001`) == TRUE |
is.na(`2006`) == TRUE)
```
And map 2006 census (2003 Representation order) with _2006 parliament data._
#### Merge 2006 census (2003 Representation order) with 2011 census (2003 Representation order) to map with _2008 parliament data._
```{r match ro2003_2}
d11_clean <- d11_clean %>%
spread(age, value)
ro2003_2 <- rbind(d06_clean, d11_clean) %>%
gather(age, value, `0`:`100`) %>%
spread(census, value)
length(unique(ro2003_2$dist_nb))
length(unique(ro2003_2$dist_name))
check <- ro2003_2 %>%
filter(is.na(`2006`) == TRUE |
is.na(`2011`) == TRUE)
```
And map 2011 census (2003 Representation order) with _2011 parliament data._
#### Merge 2011 census (2013 Representation order) 2016 census (2013 Representation order) to map with _2015 parliament data._
```{r match ro2013}
d11_2_clean <- d11_2_clean %>%
spread(age, value)
d16_clean <- d16_clean %>%
spread(age, value)
ro2013 <- rbind(d11_2_clean, d16_clean) %>%
gather(age, value, `0`:`100`) %>%
spread(census, value)
length(unique(ro2013$dist_nb))
check <- ro2013 %>%
filter(is.na(`2011`) == TRUE |
is.na(`2016`) == TRUE) # oops
ro2013 <- ro2013 %>%
gather(year, value, `2011`:`2016`) %>%
drop_na() %>%
dplyr::group_by(dist_nb, age) %>%
mutate(new_name = dist_name[year == 2011]) %>% # recode districts with different names, use 2011 names
dplyr::ungroup() %>%
mutate(dist_name = new_name) %>%
select(-new_name) %>%
spread(year, value)
length(unique(ro2013$dist_nb))
length(unique(ro2013$dist_name))
check <- ro2013 %>%
filter(is.na(`2011`) == TRUE |
is.na(`2016`) == TRUE) # all good
```
### 3) Interpolation of Values for Years In-Between Censuses
Election years sometimes (often) fall in-between censuses. We will interpolate the number of people in each age group to years between censuses, so that we have 'truer' values for election years. We will do this for each of the five datasets we merged in the previous step.
First, we need to reshape the data from long to wide.
```{r}
ro1987_imputation <- ro1987 %>%
gather(year, value, `1991`:`1996`) %>%
mutate(year = as.integer(year)) %>%
mutate(ro = "ro1987")
ro1996_imputation <- ro1996 %>%
gather(year, value, `1996`:`2001`) %>%
mutate(year = as.integer(year)) %>%
mutate(ro = "ro1996")
ro2003_imputation <- ro2003 %>%
gather(year, value, `2001`:`2006`) %>%
mutate(year = as.integer(year)) %>%
mutate(ro = "ro2003")
ro2003_2_imputation <- ro2003_2 %>%
gather(year, value, `2006`:`2011`) %>%
mutate(year = as.integer(year)) %>%
mutate(ro = "ro2003_2")
ro2013_imputation <- ro2013 %>%
gather(year, value, `2011`:`2016`) %>%
mutate(year = as.integer(year)) %>%
mutate(ro = "ro2013")
imputation_d <- rbind(ro1987_imputation, ro1996_imputation, ro2003_imputation, ro2003_2_imputation, ro2013_imputation) # creating one big dataframe
```
Then, we make the value imputation. This is a function I found online. It seems to work well, but suggestions as to how to do this otherwise would be more than welcome (is there a built-in function or package achieving this with fewer lines of code?)
```{r}
expand_data <- function(x) {
years <- min(imputation_d$year):max(imputation_d$year)
btw_years <- 1
grid <- expand.grid(btw_year = btw_years, year = years)
x$btw_year <- 1
merged <- grid %>% left_join(x, by = c('year', 'btw_year'))
merged$dist_name <- x$dist_name[1]
merged$dist_nb <- x$dist_nb[1]
merged$age <- x$age[1]
merged$ro <- x$ro[1]
return(merged)
}
interpolate_data <- function(data) {
xout <- 1:nrow(data)
y <- data$value
interpolation <- approx(x = xout[!is.na(y)], y = y[!is.na(y)], xout = xout)
data$yhat <- interpolation$y
return(data)
}
expand_and_interpolate <- function(x) interpolate_data(expand_data(x))
imputation_data <- imputation_d %>% group_by(dist_name, dist_nb, age, ro) %>% do(expand_and_interpolate(.))
print(as.data.frame(imputation_data))