-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01_tidyingOriginalData.Rmd
1369 lines (1053 loc) · 38.4 KB
/
01_tidyingOriginalData.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: "ONS LAD 2019 data cleaning"
author: "Luis Chaves"
date: "Summer 2020"
output: html_document
---
# Data cleaning report
```{r include = FALSE}
knitr::opts_chunk$set(message = F, warning = F)
```
## Load libraries
```{r }
library(tidyverse)
library(lubridate)
library(readxl)
theme_set(theme_bw())
library(imputeTS)# time series imputation
library(naniar)# for missing data visualisation
library(knitr) # for rmarkdown rendering
source('time_impute.R', echo = T) # time series wrapper imputation function
source('updateCodes.R', echo = T)
```
## Load Data
```{r }
# deaths = read.csv('OriginalData/deathrecords2020.csv') # caveat: only 2020
# deaths = read.csv('OriginalData/DEATHS02010_2019.csv') # caveat: only by wider regions (around 13)
# -- not using for now as only 2020 deaths
lifeexpect = read.csv('OriginalData/lifeexpectancies.csv')
# population = read_xlsx('OriginalData/popestimates.xlsx',
# sheet = 'Dataset',
# range = cell_rows(c(3, 121433)))
population = read.csv('OriginalData/POPULATION2018_2019.csv')
suicides = read.csv('OriginalData/suicide2018.csv')
wellbeing = read.csv('OriginalData/wellbeing.csv')
work = read.csv('OriginalData/working.csv')
work_ts = read.csv('OriginalData/working_time_series.csv')
gdp = read_xlsx('OriginalData/regionalgrossdomesticproductgdplocalauthorities.xlsx',
sheet = 'Table 5',
range = cell_rows(c(2, 384)))
unemployment = read_xls('OriginalData/unemployment.xls',
range = 'A3:HA375', sheet = 3)
```
## Clean data
Here I take data cleaning on a case-by-case basis: tidying and imputing each data set at a time,
indepently of each other. A few comments that apply to all the ONS datasets: all data sets appear to have
redundant columns (as in duplicates), secondly for some of them the data corresponds to an interval and
for some others the data is available for every year.
### Deaths table (not used in the end)
```{r }
# deaths table: some columns are duplicate so we remove those, we also change the week strings to week numbers
# str(deaths)
#
# deaths = deaths %>%
# select(-c(Data.Marking,calendar.years,week, cause.of.death, place.of.death, registration.or.occurrence)) %>%
# rename(Deaths = V4_1, year = time, areaCode = admin.geography,
# areaName = geography, deathCause = causeofdeath,
# deathPlace = placeofdeath, week = week.number) %>%
# mutate(week = as.integer(str_replace(week, 'week-', '')))
```
### Life expectancy table
#### Visualise raw data
```{r }
str(lifeexpect)
```
#### Modify initial data
As there are many duplicated columns, we will delete those that are either duplicated or empty
and give better names to the ones we keep, as well as changing the type of numeric variables that
are registered as strings
```{r }
lifeexpect = lifeexpect %>%
select(-c(Data_Marking,
two.year.intervals,
life.expectancy.variable,
birth.cohort)) %>%
rename(Value = V4_3,
lowerCI = lower.confidence.limit,
upperCI = upper.confidence.limit,
year = time,
areaCode = admin.geography,
areaName = geography,
LEvariable = lifeexpectancyvariable,
cohort = birthcohort) %>%
mutate(lowerCI = as.numeric(lowerCI),
upperCI = as.numeric(upperCI))
```
#### Modify year intervals to years
The life expectancy information is available in the year intervals `r{unique(lifeexpect$year)}`,
to be consistent with the datasets that are available for every year we turn intervals into years. We do this
by taking the upper value of each interval as the year column. e.g.: turning 2013-15 to 2015
and 2014-16 to 2016 and so forth
```{r }
lifeexpect$year = as.numeric(lapply(strsplit(lifeexpect$year, '-'), '[[',1))+2
```
#### Check missing data with respect to several factors
Now we check missing data in the `Value` column by cohort, type of life expectancy variable and year
```{r }
kable(table(is.na(lifeexpect$Value), lifeexpect$cohort)) # all cohorts with same amount of data
kable(table(is.na(lifeexpect$Value), lifeexpect$LEvariable)) # lifeexpectancy with the least missing data
kable(table(is.na(lifeexpect$Value), lifeexpect$year)) # 2017 with most missing data
```
#### Shortening strings that are too long
```{r }
lifeexpect = lifeexpect %>%
mutate(LEvariable = ifelse(LEvariable == 'Disability-free life expectancy',
'DFLE',
ifelse(LEvariable == 'Healthy life expectancy',
'HLE',
'LE')),
cohort = ifelse(cohort == 'Females at age 65',
'FemAt65',
ifelse(cohort == 'Males at age 65',
'MaleAt65',
ifelse(cohort == 'Females at birth',
'FemAtBirth',
'MaleAtBirth'))))
```
#### Check number of entries with missing values for all years
Here we wish to know how many entries, defined by unique combinations of the local authority code (`areaCode`),
the life expectancy(LE) variable (`LEvariable`, e.g. healthy LE, Disability-free LE...) and cohort (`cohort`, e.g. Male at birth,
Female at 65...) have no available values (aka all values missing) for all available years.
```{r }
count = 0
combs = 0
for (reg in unique(lifeexpect$areaCode))
for (var in unique(lifeexpect$LEvariable))
for(coh in unique(lifeexpect$cohort))
{
combs = combs +1
if (all(is.na(lifeexpect %>% filter(areaCode == reg, LEvariable == var, cohort == coh) %>% select(Value)))){
count = count+1
}
}
cat(paste(count, 'combinations out of', combs, 'combinations have all missing entries'))
```
#### Missingness count by number of missing year entries
```{r }
lifeexpect %>%
group_by(areaCode,
LEvariable,
cohort) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value)),
ProprortionOfMissingEntries = paste0(round(mean(is.na(Value)),3)*100,' %')) %>%
group_by(NumberOfMissingEntries,
ProprortionOfMissingEntries) %>%
summarise(Count = n()) %>%
kable()
```
#### Time series imputation
First we order the data by year, the time series works assuming the data is ordered.
```{r }
lifeexpect = lifeexpect %>% arrange(areaCode, LEvariable, cohort, year)
lifeexpect = time_impute(lifeexpect, areaCode, LEvariable, cohort,
year_column = 'year')
```
#### Final check on missingness count
```{r }
lifeexpect %>%
group_by(areaCode,
LEvariable,
cohort) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value)),
ProportionOfMissingEntries = mean(is.na(Value))) %>%
group_by(NumberOfMissingEntries,
ProportionOfMissingEntries) %>%
summarise(Count = n()) %>%
kable()
```
#### Gather data in its final form
We finally filter for the latest year (in this case 2017) and pivot the data to get a tidy format. We
also keep a copy of the tidy time-series data (just in case)
```{r }
lifeexpect_time = lifeexpect %>%
pivot_wider(names_from = c(LEvariable, cohort),
values_from = c(Value, lowerCI, upperCI))
lifeexpect = lifeexpect_time %>%
filter(year == 2017)
str(lifeexpect)
```
#### Visualise missing data
```{r }
vis_miss(lifeexpect) + coord_flip()
```
We notice the variables DFLE and HLE have a lot of missingness hence we only keep the LE variables
```{r }
lifeexpect_time = lifeexpect_time %>% select(year, areaCode, areaName, contains('_LE_'))
lifeexpect = lifeexpect %>% select(year, areaCode, areaName, contains('_LE_'))
```
#### Update old area codes
Pass through custom function to update old codes, then combine the entries with matching area name
and area code
##### For lifeexpect
```{r }
lifeexpect = updateCodes(lifeexpect)
combs_dup = lifeexpect %>%
group_by(areaCode, areaName, year) %>% summarise(duplicat = n()>1)
print(
lifeexpect[lifeexpect$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(2,3,6,7)])
```
This function combines entries by taking the mean when they are duplicated
```{r }
for (row in which(combs_dup$duplicat==T)){
entry = combs_dup[row,]
lifeexpect[(lifeexpect$areaCode == entry$areaCode &
lifeexpect$areaName == entry$areaName &
lifeexpect$year == entry$year),
!colnames(lifeexpect) %in% c('areaCode','areaName', 'year')] =
t(apply(lifeexpect[(lifeexpect$areaCode == entry$areaCode &
lifeexpect$areaName == entry$areaName &
lifeexpect$year == entry$year),
!colnames(lifeexpect) %in% c('areaCode','areaName', 'year')],2,mean))
}
print(
lifeexpect[lifeexpect$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(2,3,6,7)])
```
Finally, select unique rows as we have generated duplicated entries in the previous step
```{r }
lifeexpect = lifeexpect %>% distinct()
```
##### For lifeexpecttime
```{r }
lifeexpect_time = updateCodes(lifeexpect_time)
combs_dup = lifeexpect_time %>%
group_by(areaCode, areaName, year) %>% summarise(duplicat = n()>1)
print(
lifeexpect_time[lifeexpect_time$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(3,6,7)])
```
This function combines entries by taking the mean when they are duplicated
```{r }
for (row in which(combs_dup$duplicat==T)){
entry = combs_dup[row,]
lifeexpect_time[(lifeexpect_time$areaCode == entry$areaCode &
lifeexpect_time$areaName == entry$areaName &
lifeexpect_time$year == entry$year),
!colnames(lifeexpect_time) %in% c('areaCode','areaName', 'year')] =
t(apply(lifeexpect_time[(lifeexpect_time$areaCode == entry$areaCode &
lifeexpect_time$areaName == entry$areaName &
lifeexpect_time$year == entry$year),
!colnames(lifeexpect_time) %in% c('areaCode','areaName', 'year')],2,mean))
}
print(
lifeexpect_time[lifeexpect_time$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(3,6,7)])
```
Finally, select unique rows as we have generated duplicated entries in the previous step
```{r }
lifeexpect_time = lifeexpect_time %>% distinct()
```
### Population table
Out if this dataset we will extract information regarding age statistics and population size
```{r }
tail(population)
```
We notice below that the column containing the population estimates contains no missing values which is great
```{r }
sum(is.na(population$v4_0)) # no missing values, thank god, no need for imputation
```
#### (un)select, filter, rename
```{r }
population = population %>%
select(-c(calendar.years,
mid.year.pop.sex,
mid.year.pop.age))%>%
rename(areaName = geography,
areaCode = admin.geography,
Value = v4_0,
year = time)
```
##### Update old codes
In this case we update the codes before tidying because we are going to perform aggregations later
```{r }
population = updateCodes(population)
```
#### Visualise the age distribution
Distribution of age coloured by gender for 9 random local authority districts
```{r }
population %>%
filter(year == 2018) %>%
filter(sex != 'All',
age != 'Total',
areaName %in% sample(areaName, 9)) %>%
mutate(age = as.numeric(ifelse(age == '90+', 90, age))) %>%
ggplot(aes(x = age,
y = Value,
fill = sex))+
geom_col()+
facet_wrap(vars(areaName), scales = 'free')+
scale_x_continuous(breaks = seq(0,100, by = 20))
```
#### Check if all ages are represented
Check if there are any holes in the age records
```{r }
unique_ages = data.matrix(unique(population %>%
filter(age != 'Total') %>%
mutate(age = as.numeric(ifelse(age == '90+', 90, age))) %>%
select(age)))
all(unique_ages %in% c(0:90))
```
For population I can extract:
* age info:
* mean
* median
* mode: when calculating the mode, sometimes for some miracle
of the universe the frequency for a given age group and a given sex is the same
(See Wrexham in population df as they have 1015 for 46 and 47 y/o males), in these cases
I'm taking the mean for those cases (i.e. 46.5 in above example)
* stdev
* ~~range~~
* ~~max~~
* ~~min~~ in practice all LADs have at least one 0 year old and one 90+ year old
* age bins, number of people in each age bin
* pop info:
* total
* total males
* total females
All stratified by gender and not stratified
We define the age bins arbitrarily to represent: children and teens (0-16 y/o), young adults (17-29 y/o),
adults (30-63 y/o), old (64-80) and very old (80+).
To calculate things like median and mode I actually 'explode' the age column with the `rep()` function
getting the count for each age from the `Value` column and then calculate the statistics in question
```{r }
age_time = population %>%
filter(age != 'Total' & sex != 'All') %>%
mutate(age = as.numeric(ifelse(age == '90+', 90, age))) %>%
group_by(year,
areaCode,
areaName,
sex) %>%
summarise(TotalPeople = sum(Value),
MeanAge = sum(age*Value)/TotalPeople,
MedianAge = median(rep(age,Value)),
ModeAge = mean(age[which(Value == max(Value))]),
stdevAge = sd(rep(age,Value)),
NumberOfTeens = sum(Value[which(age<17)]),
NumberOfYoungAdults = sum(Value[which(age>=17 & age<30)]),
NumberOfAdults = sum(Value[which(age>=30 & age<64)]),
NumberOfOld = sum(Value[which(age>=64 & age<81)]),
NumberOfVeryOld = sum(Value[which(age>80)]))
age = age_time %>% filter(year == 2018)
age_time = age_time %>%
pivot_wider(names_from = sex,
values_from = c(TotalPeople,
MeanAge,
MedianAge,
ModeAge,
stdevAge,
NumberOfTeens,
NumberOfYoungAdults,
NumberOfAdults,
NumberOfOld,
NumberOfVeryOld)
)
age = age %>%
pivot_wider(names_from = sex,
values_from = c(TotalPeople,
MeanAge,
MedianAge,
ModeAge,
stdevAge,
NumberOfTeens,
NumberOfYoungAdults,
NumberOfAdults,
NumberOfOld,
NumberOfVeryOld)
)
```
#### Total(Female+Male) population statistics
```{r }
agetotal_time = population %>%
filter(age != 'Total' & sex != 'All') %>%
mutate(age = as.numeric(ifelse(age == '90+', 90, age))) %>%
group_by(year,
areaCode,
areaName) %>% # note we are not aggregating by sex
summarise(TotalPeople = sum(Value),
MeanAge = sum(age*Value)/TotalPeople,
MedianAge = median(rep(age,Value)),
ModeAge = mean(age[which(Value == max(Value))]),
stdevAge = sd(rep(age,Value)),
NumberOfTeens = sum(Value[which(age<17)]),
NumberOfYoungAdults = sum(Value[which(age>=17 & age<30)]),
NumberOfAdults = sum(Value[which(age>=30 & age<64)]),
NumberOfOld = sum(Value[which(age>=64 & age<81)]),
NumberOfVeryOld = sum(Value[which(age>80)]))
agetotal = agetotal_time %>% filter(year == 2018)
colnames(agetotal_time)[4:ncol(agetotal_time)] = paste0(
colnames(agetotal_time)[4:ncol(agetotal_time)], '_All')
colnames(agetotal)[4:ncol(agetotal)] = paste0(
colnames(agetotal)[4:ncol(agetotal)], '_All')
```
#### Merge into a single table
```{r }
popclean_time = merge(age_time, agetotal_time, by = c('year','areaCode','areaName'))
popclean = merge(age, agetotal, by = c('year','areaCode','areaName'))
```
#### Update old area codes
Pass through custom function to update old codes, then combine the entries with matching area name
and area code
##### For population table
```{r }
popclean = updateCodes(popclean)
combs_dup = popclean %>%
group_by(areaCode, areaName,year) %>% summarise(duplicat = n()>1)
# In this case luckily we had no bad entries
print(
popclean[popclean$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(3,6,7)])
```
##### For popclean_time table
```{r }
popclean_time = updateCodes(popclean_time)
combs_dup = popclean_time %>%
group_by(areaCode, areaName,year) %>% summarise(duplicat = n()>1)
print(
popclean_time[popclean_time$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(3,6,7)])
```
### Suicides table
```{r }
str(suicides)
```
#### Select, rename
```{r }
suicides = suicides %>%
select(-calendar.years) %>%
rename(Value = V4_0,
year = time,
areaCode = admin.geography,
areaName = geography)
```
#### Again no NAs
```{r }
sum(is.na(suicides$Value)) # no NAs good
```
According the command below all locations have data available for all years
```{r }
sum(is.na(suicides %>%
pivot_wider(names_from = year, values_from = Value)))
```
#### Time-series plot of a few LADs
```{r }
suicides %>%
filter(areaName %in% sample(areaName, 9)) %>%
ggplot(aes(x = year, y = Value))+
geom_point()+
facet_wrap(vars(areaName))
```
#### Update codes
```{r }
suicides = updateCodes(suicides)
combs_dup = suicides %>%
group_by(areaCode, areaName, year) %>% summarise(duplicat = n()>1)
print(
suicides[suicides$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(1)])
```
# No duplicates again!
#### Store time-series and most up-to-date one
```{r }
suicides_time = suicides %>% rename(NumberOfSuicides = Value)
suicides = suicides_time %>% filter(year == 2018)
```
### Wellbeing table
#### Evaluate content of table
```{r }
tail(wellbeing)
```
#### Missing data
We observe quite a lot of data missingness here
```{r }
sum(is.na(wellbeing$V4_3))
mean(is.na(wellbeing$V4_3))
```
#### Select, rename, mutate
```{r }
wellbeing = wellbeing %>%
select(-c(Data.Marking,
yyyy.yy,
wellbeing.measureofwellbeing,
wellbeing.estimate)) %>%
rename(Value = V4_3,
lowerCI = Lower.limit,
upperCI = Upper.limit,
year = time,
areaCode = admin.geography,
areaName = geography,
WellbeingMetric = allmeasuresofwellbeing,
EstimateBin = estimate) %>%
mutate(lowerCI = as.numeric(lowerCI),
upperCI = as.numeric(upperCI))
```
#### Turn year interval to year
Same operation that we did for the `lifeexpect` table, here the intervals are only 2 years long though.
(e.g. 2014-15 --> 2015)
```{r }
wellbeing$year = as.numeric(lapply(strsplit(wellbeing$year, '-'), '[[',1))+1
```
#### Variable selection
The wellbeing data is very rich, this data was gathered by running a survey with 4 self-assesed
questions. For each question the user can score a value between 0 and 10. The `wellbeing` table
contains the average score for each category
(i.e. `r{paste(unique(wellbeing$wellbeing.measureofwellbeing), collapse= ', ')}`) as well as the proportion
of people in different bins (i.e. `r{paste(unique(wellbeing$estimate), collapse= ', ')}`). I believe the average
score is more interpretable than the bins and more concise, though there are some caveats to this. Read more
about the methodology behing these metrics in
[the ONS site](https://www.ons.gov.uk/peoplepopulationandcommunity/wellbeing/methodologies/personalwellbeingintheukqmi)
```{r }
wellbeing = wellbeing %>% filter(EstimateBin == 'Average (mean)')
```
#### Evaluate missingness after filtering
```{r }
sum(is.na(wellbeing$Value)) # 117 missing values
```
#### Missingness by area and by wellbeing metric
In this case if the output is 8, all entries are missing for all 8 years the variable was measured
```{r }
wellbeing %>%
group_by(areaCode,
WellbeingMetric) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value)),
ProportionOfMissingEntries = mean(is.na(Value))) %>%
group_by(NumberOfMissingEntries,
ProportionOfMissingEntries) %>%
summarise(Count = n()) %>%
kable()
```
#### Missingness by year
```{r }
wellbeing %>%
group_by(year) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value)),
ProportionOfMissingEntries = mean(is.na(Value))) %>%
kable()
```
#### Time-series plot
```{r }
wellbeing %>%
filter(areaName %in% sample(areaName, 9)) %>%
ggplot(aes(x = year,
y = Value,
color = WellbeingMetric)) +
geom_point() +
facet_wrap(vars(areaName))
```
#### Edge-cases
The LADs with all missingness are the City of london and the Isles of Scilly. These two often have
no available data from the ONS
#### Time-series imputation
Order the data before imputation (just in case)
```{r }
wellbeing = wellbeing %>% arrange(areaCode, WellbeingMetric, year)
wellbeing = time_impute(wellbeing, areaCode, WellbeingMetric)
```
##### Results (as expected)
```{r }
wellbeing %>%
group_by(areaCode,
WellbeingMetric) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value)),
ProportionOfMissingEntries = mean(is.na(Value))) %>%
group_by(NumberOfMissingEntries,
ProportionOfMissingEntries) %>%
summarise(Count = n()) %>%
kable()
```
(Updated) missingness by year
```{r }
wellbeing %>%
group_by(year) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value))) %>%
kable()
```
#### Gather data
```{r }
wellbeing_time = wellbeing %>%
mutate(Range = upperCI - lowerCI) %>%
select(Value,
Range,
year,
areaCode,
areaName,
WellbeingMetric) %>%
pivot_wider(names_from = WellbeingMetric,
values_from = c(Value, Range))
```
#### Update codes
```{r }
wellbeing_time = updateCodes(wellbeing_time)
combs_dup = wellbeing_time %>%
group_by(areaCode, areaName, year) %>% summarise(duplicat = n()>1)
print(
wellbeing_time[wellbeing_time$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(1,2,3,4)] %>%
arrange(areaCode, areaName,year), n = 100)
```
Many duplicates now
#' This function combines entries by taking the __mean__ when they are duplicated
```{r }
for (row in which(combs_dup$duplicat==T)){
entry = combs_dup[row,]
wellbeing_time[(wellbeing_time$areaCode == entry$areaCode &
wellbeing_time$areaName == entry$areaName &
wellbeing_time$year == entry$year),
!colnames(wellbeing_time) %in% c('areaCode','areaName', 'year')] =
t(apply(wellbeing_time[(wellbeing_time$areaCode == entry$areaCode &
wellbeing_time$areaName == entry$areaName &
wellbeing_time$year == entry$year),
!colnames(wellbeing_time) %in% c('areaCode','areaName', 'year')],2,mean))
}
print(
wellbeing_time[wellbeing_time$areaCode %in%
combs_dup$areaCode[combs_dup$duplicat==T],c(1,2,3,4)])
```
Finally, select unique rows as we have generated duplicated entries in the previous step
```{r }
wellbeing_time = wellbeing_time %>% distinct()
wellbeing = wellbeing_time %>%
filter(year == 2019)
```
### Work table
The ASHE work table contains a column called coefficient of variation which is an estimate of the
variation within the sample and it helps evaluate whether the sample can be considered a good
representation of the population. Find explanation of the Coefficient of variation (CV) column
[here](https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/methodologies/annualsurveyofhoursandearningslowpayandannualsurveyofhoursandearningspensionresultsqmi)
Moreover, in this section we have two tables, `work` and `work_ts`, the 1st one contains info for 2019 and the second one contains
data from earlier years to enable us to impute the 2019 data.
```{r }
str(work)
```
#### Select, rename, mutate
```{r }
work = work %>%
select(-c(Data.Marking,
calendar.years,
ashe.working.pattern,
ashe.sex,
ashe.statistics,
ashe.workplace.or.residence,
ashe.hours.and.earnings,
ashe.working.pattern)) %>%
rename(Value = V4_2,
year = time,
areaCode = admin.geography,
areaName = geography,
CoefficientOfVariation = CV) %>%
mutate(CoefficientOfVariation = as.numeric(CoefficientOfVariation))
```
#### Explore a few columns
```{r }
unique(work$hoursandearnings)
unique(work$workplaceorresidence)
unique(work$workingpattern)
unique(work$statistics)
```
#### Many, many, many statistics available
Too many stats are available as seen above, we are only interested in a few. We select mean, median,
10th and 90th percentile
```{r }
work = work %>%
filter(statistics %in% c('Mean', 'Median', '10th percentile', '90th percentile'),
workplaceorresidence == 'Workplace')
```
#### Select earnings metric
From the above command we see that hourly pay has the least missingness so we'll go
with that one
```{r }
work %>%
group_by(hoursandearnings) %>%
summarise(NumberOfMissingEntries = mean(is.na(Value))) %>%
kable()
```
Now we evaulate the missingess of each earning metric per statistic to see if
some combination of these is missing at an unacceptable rate
```{r }
work %>%
group_by(hoursandearnings, statistics) %>%
summarise(NumberOfMissingEntries = mean(is.na(Value))) %>%
ggplot(aes(x = hoursandearnings,
y = statistics,
fill = NumberOfMissingEntries,
label = round(NumberOfMissingEntries,2)))+
geom_tile()+
geom_text(color = 'white')+
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```
this last graph reveals that the 90th and the 10th percentile stats have too much
missingess hence I am dropping them, it also show how Hourly pay is the
most covered stat
Based on previous graph I decided to choose hourly pay
and mean and median only
```{r }
work = work %>%
filter(hoursandearnings == 'Hourly pay - Gross',
statistics %in% c('Median', 'Mean'))
```
Given that now the `hoursandearnings` and the `worplaceorresidence` columns contain
unique values only I drop them
```{r }
work = work %>% select(-c(hoursandearnings, workplaceorresidence))
```
#### Work time-series table
##### Select, rename, mutate
```{r }
work_ts = work_ts %>%
select(-c(Data_Marking,
calendar.years,
ashe.working.pattern,
ashe.sex,
ashe.statistics,
ashe.workplace.or.residence,
ashe.hours.and.earnings,
ashe.working.pattern)) %>%
rename(Value = V4_2,
year = time,
areaCode = admin.geography,
areaName = geography,
CoefficientOfVariation = CV) %>%
mutate(CoefficientOfVariation = as.numeric(CoefficientOfVariation))
```
Filter the same way as for the `work` dataframe
```{r }
work_ts = work_ts %>%
filter(statistics %in% c('Mean', 'Median', '10th percentile', '90th percentile'),
workplaceorresidence == 'Workplace')
work_ts = work_ts %>%
filter(hoursandearnings == 'Hourly pay - Gross',
statistics %in% c('Median', 'Mean'))
work_ts = work_ts %>% select(-c(hoursandearnings, workplaceorresidence))
```
##### Check for any disparity between the areas covered by both of these dataframes
```{r }
unique(work$areaName[!(work$areaName %in% work_ts$areaName)])
```
Now merge work (data from 2019 only) and work_ts (2016 through 2018)
```{r }
work = rbind(work, work_ts)
```
#### Start exploring dataset
I believe not all towns have entries for all years
in theory there should be 4 entries (2016-19) per combination of
areacode, stat, sex and working pattern
```{r }
work %>%
group_by(areaCode,
statistics,
sex,
workingpattern) %>%
summarise(NumberOfYearsWithAvailableData = n()) %>% ## this takes the numbers
# of entries per unique combination of the variables in the group_by
group_by(NumberOfYearsWithAvailableData) %>%
summarise(Count = n()) %>%
kable()
```
As you can see in the above table for some combinations
there are only 3 available variables hence 3 missing variables
represent 100% where as in other cases 4 missing varialbes represent
100% of variables
```{r }
work %>%
group_by(areaCode,
statistics,
sex,
workingpattern) %>%
summarise(NumberOfMissingEntries = sum(is.na(Value)),
ProportionOfMissingEntries = mean(is.na(Value))) %>%
group_by(NumberOfMissingEntries,
ProportionOfMissingEntries) %>%
summarise(Count = n()) %>%
kable()