-
Notifications
You must be signed in to change notification settings - Fork 0
/
Population estimates using the BSAS with R.html
1120 lines (1088 loc) · 78.8 KB
/
Population estimates using the BSAS with R.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.4.553">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<meta name="author" content="UK Data Service">
<title>Basic population estimates with British Social Attitudes Survey data using R</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="Population estimates using the BSAS with R_files/libs/clipboard/clipboard.min.js"></script>
<script src="Population estimates using the BSAS with R_files/libs/quarto-html/quarto.js"></script>
<script src="Population estimates using the BSAS with R_files/libs/quarto-html/popper.min.js"></script>
<script src="Population estimates using the BSAS with R_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="Population estimates using the BSAS with R_files/libs/quarto-html/anchor.min.js"></script>
<link href="Population estimates using the BSAS with R_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="Population estimates using the BSAS with R_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="Population estimates using the BSAS with R_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="Population estimates using the BSAS with R_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="Population estimates using the BSAS with R_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<style>html{ scroll-behavior: smooth; }</style>
<style>
.quarto-title-block .quarto-title-banner h1,
.quarto-title-block .quarto-title-banner h2,
.quarto-title-block .quarto-title-banner h3,
.quarto-title-block .quarto-title-banner h4,
.quarto-title-block .quarto-title-banner h5,
.quarto-title-block .quarto-title-banner h6
{
color: #742082;
}
.quarto-title-block .quarto-title-banner {
color: #742082;
background: white;
}
</style>
<link rel="stylesheet" href="ukds.css">
</head>
<body>
<header id="title-block-header" class="quarto-title-block default toc-left page-columns page-full">
<div class="quarto-title-banner page-columns page-full">
<div class="quarto-title column-body">
<h1 class="title">Basic population estimates with British Social Attitudes Survey data using R</h1>
</div>
</div>
<div class="quarto-title-meta">
<div>
<div class="quarto-title-meta-heading">Author</div>
<div class="quarto-title-meta-contents">
<p>UK Data Service </p>
</div>
</div>
<div>
<div class="quarto-title-meta-heading">Published</div>
<div class="quarto-title-meta-contents">
<p class="date">April 2024</p>
</div>
</div>
</div>
</header><div id="quarto-content" class="page-columns page-rows-contents page-layout-article toc-left">
<div id="quarto-sidebar-toc-left" class="sidebar toc-left">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">Table of contents</h2>
<ul>
<li><a href="#getting-started" id="toc-getting-started" class="nav-link active" data-scroll-target="#getting-started">Getting started</a></li>
<li><a href="#explore-the-dataset" id="toc-explore-the-dataset" class="nav-link" data-scroll-target="#explore-the-dataset">1. Explore the dataset</a></li>
<li><a href="#missing-values" id="toc-missing-values" class="nav-link" data-scroll-target="#missing-values">2. Missing values</a></li>
<li><a href="#compare-unweighted-and-weighted-proportions" id="toc-compare-unweighted-and-weighted-proportions" class="nav-link" data-scroll-target="#compare-unweighted-and-weighted-proportions">3. Compare unweighted and weighted proportions</a></li>
<li><a href="#confidence-intervals" id="toc-confidence-intervals" class="nav-link" data-scroll-target="#confidence-intervals">4. Confidence intervals</a></li>
<li><a href="#answers" id="toc-answers" class="nav-link" data-scroll-target="#answers">Answers</a></li>
</ul>
</nav>
</div>
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
</div>
<main class="content quarto-banner-title-block" id="quarto-document-content">
<p>This exercise is part of the <a href="https://trainingmodules.ukdataservice.ac.uk/attitudes/#/" target="_blank" rel="noopener">‘Introduction to the British Social Attitudes Survey (BSA)’</a> online module. In the exercise, we examine data from the 2020 British Social Attitudes survey to find out:</p>
<ul>
<li><p>what proportion of respondents said they voted remain in the EU Referendum?</p></li>
<li><p>whether people think the government should raise taxes and spend more or reduce tax and cut social expenditures?</p></li>
<li><p>how much people think they’ll get from the State pension?</p></li>
</ul>
<p>Answers to the questions asked throughout the exercise can be found at the end of the page.</p>
<section id="getting-started" class="level3">
<h3 class="anchored" data-anchor-id="getting-started">Getting started</h3>
<p>Data can be downloaded from the <a href="https://beta.ukdataservice.ac.uk/datacatalogue/studies/study?id=9005" target="_blank" rel="noopener">UK Data Service website</a> following <a href="https://ukdataservice.ac.uk/help/registration/registration-login-faqs/" target="_blank" rel="noopener">registration</a>. Download the compressed folder, unzip and save it somewhere accessible on your computer.</p>
<p>The examples below assume that the dataset has been saved in a new folder named <em>UKDS</em> on your Desktop (Windows computers). The path would typically be <code>C:\Users\YOUR_USER_NAME\Desktop\UKDS</code>. Feel free to change it to the location that best suits your needs.</p>
<p>We begin by loading the R packages needed for the exercise and set the working directory.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">library</span>(dplyr) <span class="do">### Data manipulation functions</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="fu">library</span>(haven) <span class="do">### Functions for importing data from </span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> <span class="do">### commercial packages</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="fu">library</span>(Hmisc) <span class="do">### Extra statistical functions</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="do">### Setting up the working directory</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="do">### Change the setwd() command to match the location </span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a><span class="do">### of the data on your computer </span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a><span class="do">### if required </span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="fu">setwd</span>(<span class="st">"C:\Users\Your_Username_here</span><span class="sc">\"</span><span class="st">)</span></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a><span class="st">getwd()</span></span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a><span class="st"># Opening the BSA dataset in SPSS format</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a><span class="st">bsa20<-read_spss(</span></span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a><span class="st"> 'UKDA-9005-spss/spss/spss25/bsa2020_archive.sav'</span></span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a><span class="st"> ) </span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p><code>[1] C:\Users\Your_Username_here\</code></p>
</section>
<section id="explore-the-dataset" class="level3">
<h3 class="anchored" data-anchor-id="explore-the-dataset">1. Explore the dataset</h3>
<p>Start by getting an overall feel for the data. Either inspect variables and cases in the data editor or use the code below to produce a summary of all the variables in the dataset.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="do">### Gives the number of rows (observations) </span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="do">### and columns (variables)</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="fu">dim</span>(bsa20) </span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 3964 210</code></pre>
</div>
<div class="sourceCode cell-code" id="cb4"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a> <span class="do">### List variable names in their actual </span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a> <span class="do">### order in the dataset</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(bsa20)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [1] "serial" "QnrVersion" "RespSx2cat" "RespAgeE" "MarStat6"
[6] "REconFW01" "REconFW02" "REconFW03" "REconFW04" "REconFW05"
[11] "REconFW06" "REconFW07" "REconFW08" "REconFW09" "REconFW10"
[16] "REconFW11" "EMPSTAT" "Employ" "Superv" "EmpOCC"
[21] "TenureE" "SupParty" "ClosePty" "PARTYFW" "Idstrng"
[26] "RemLea" "RemLeaCl" "RemLeaSt" "Politics" "ConLabDf"
[31] "VoteDuty" "SocTrust" "EngParl" "ScotPar2" "ECPolicy2"
[36] "Spend1" "Spend2" "SocBen1" "SOCBEN2" "DOLE"
[41] "TAXSPEND" "WkMent" "WkPhys" "HProbRsp" "PhsRetn"
[46] "PhsRecov" "MntRetn" "MntRecov" "HCWork21" "HCWork22"
[51] "HCWork23" "HCWork24" "HCWork25" "HCWork26" "HCWork28"
[56] "HCWork29" "HCWork213" "HCWork214" "HCWork215" "HCWork27"
[61] "CMtUnmar1" "CMtUnmar2" "CMtUnmar3" "CMtUnmar4" "CMtUnmar5"
[66] "CMtUnmar6" "CMtUnmar7" "CMtUnmar8" "CMtUnmar9" "CMtUnmar10"
[71] "CMtmar1" "CMtmar2" "CMtmar3" "CMtmar4" "CMtmar5"
[76] "CMtmar6" "CMtmar7" "CMtmar8" "CMtmar9" "CMtmar10"
[81] "ChCoSupp" "ChMIncM" "ChMIncF" "ChMCont" "RBGaran2"
[86] "RBGGov" "DigPCUn" "DigPCctl" "DigPCcon" "DigPCrsk"
[91] "DigGVun" "DigGVctl" "DigGVcon" "DigGVrsk" "DigPro"
[96] "NHSSat" "WkHmNow" "WkHmJan" "CovWkc" "CovNoWkc"
[101] "CovWkr1" "CovWkr2" "CovWkr3" "CovWkr4" "CovWkr5"
[106] "CovWkr6" "CovWk1" "CovWk2" "CovWk3" "GovtWork"
[111] "GovTrust" "CLRTRUST" "MPsTrust" "LoseTch" "VoteIntr"
[116] "PtyNMat2" "PolPart01" "PolPart02" "PolPart03" "PolPart04"
[121] "PolPart05" "PolPart06" "PolPart07" "PolPart08" "PolPart09"
[126] "PolPart10" "PolPart11" "REFHANG" "RefSyst" "UnempJob"
[131] "SocHelp" "DoleFidl" "WelfFeet" "welfhelp" "morewelf"
[136] "damlives" "proudwlf" "Redistrb" "BigBusnN" "Wealth"
[141] "RichLaw" "Indust4" "TradVals" "StifSent" "DeathApp"
[146] "Obey" "WrongLaw" "Censor" "NatIdGB" "ChAttend"
[151] "DisNew2" "DisAct" "HEdQual2" "HhldEdu" "EURefV2"
[156] "EUVOTWHO" "EURefb" "Voted" "Vote" "Anybn3"
[161] "HHincome" "Maininc5" "REarn" "HIncDif4" "RetExp"
[166] "RetExpb" "FutrWrk" "PenKnow2" "PenExp2" "PenComp"
[171] "PenIntr" "INFORET3" "WkPKnw" "WKPSav" "WkPSpn"
[176] "WPSvUs" "WPSvWw" "WPSvEas" "PrPKnw" "PrPSav"
[181] "PrPSpn" "PrPSvUs" "PrPSvWW" "PrPSvEas" "NCOutcome"
[186] "Ragecat" "Ragecat20" "DisActDV" "leftrigh" "libauth"
[191] "welfare2" "libauth2" "leftrig2" "welfgrp" "REconAct20"
[196] "REconSum20" "RaceOri4" "LegMarStE" "HhlAdGpd" "HhlChlGpd"
[201] "BestNatU2" "RetirAg3" "ReligSum20" "RlFamSum20" "EmplStatDV"
[206] "RClassGP" "serialh" "GOR" "gor2" "BSA20_wt_new"</code></pre>
</div>
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="do">### Displays the first five</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="do">### lines of a data frame</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="do">### Beware, the output might be lengthy!</span></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="fu">head</span>(<span class="fu">data.frame</span>(bsa20)) </span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> serial QnrVersion RespSx2cat RespAgeE MarStat6 REconFW01 REconFW02
1 3.211e+09 1 2 70 5 0 0
2 3.211e+09 1 2 66 1 0 0
3 3.211e+09 1 1 64 1 0 0
4 3.211e+09 1 2 43 1 0 0
5 3.211e+09 1 1 38 1 0 0
6 3.211e+09 1 2 77 1 0 0
REconFW03 REconFW04 REconFW05 REconFW06 REconFW07 REconFW08 REconFW09
1 0 0 0 0 0 0 1
2 0 0 0 0 0 0 1
3 0 0 0 0 0 0 1
4 1 0 0 0 0 0 0
5 1 0 0 0 0 0 0
6 0 0 0 0 0 0 1
REconFW10 REconFW11 EMPSTAT Employ Superv EmpOCC TenureE SupParty ClosePty
1 0 0 1 2 1 3 10 1 NA
2 0 0 1 2 1 1 1 1 NA
3 0 0 1 1 2 1 1 1 NA
4 0 0 1 3 1 3 1 2 2
5 0 0 1 3 2 2 1 2 2
6 0 0 3 NA NA 1 9 1 NA
PARTYFW Idstrng RemLea RemLeaCl RemLeaSt Politics ConLabDf VoteDuty SocTrust
1 1 2 NA NA NA 2 NA NA 1
2 2 3 NA NA NA 3 NA NA 1
3 2 3 NA NA NA 3 NA NA 1
4 2 3 NA NA NA 2 NA NA 2
5 1 3 NA NA NA 3 NA NA 2
6 1 2 NA NA NA 2 NA NA 2
EngParl ScotPar2 ECPolicy2 Spend1 Spend2 SocBen1 SOCBEN2 DOLE TAXSPEND WkMent
1 NA NA NA 2 1 1 2 1 2 1
2 NA NA NA 1 3 2 5 1 2 2
3 NA NA NA 3 1 2 3 1 2 2
4 NA NA NA 7 3 1 2 2 2 2
5 NA NA NA 7 3 2 4 2 2 1
6 NA NA NA 98 NA 1 4 2 3 2
WkPhys HProbRsp PhsRetn PhsRecov MntRetn MntRecov HCWork21 HCWork22 HCWork23
1 1 1 1 2 1 2 1 1 1
2 2 1 1 3 1 2 1 0 1
3 2 1 1 2 1 2 1 1 1
4 2 2 2 3 1 2 1 1 1
5 1 1 1 2 1 2 1 1 1
6 2 2 2 2 2 2 1 0 1
HCWork24 HCWork25 HCWork26 HCWork28 HCWork29 HCWork213 HCWork214 HCWork215
1 1 1 1 0 0 0 0 0
2 1 1 1 0 0 0 0 0
3 1 1 1 0 0 0 0 0
4 1 1 1 0 0 0 0 0
5 1 1 1 0 0 0 0 0
6 1 1 0 0 0 0 0 0
HCWork27 CMtUnmar1 CMtUnmar2 CMtUnmar3 CMtUnmar4 CMtUnmar5 CMtUnmar6
1 0 1 2 2 1 1 1
2 0 1 1 1 3 3 1
3 0 1 1 1 3 3 1
4 0 NA NA NA NA NA NA
5 0 NA NA NA NA NA NA
6 0 1 1 1 3 1 8
CMtUnmar7 CMtUnmar8 CMtUnmar9 CMtUnmar10 CMtmar1 CMtmar2 CMtmar3 CMtmar4
1 1 2 1 1 NA NA NA NA
2 1 1 3 1 NA NA NA NA
3 1 1 3 3 NA NA NA NA
4 NA NA NA NA 1 1 2 1
5 NA NA NA NA 1 1 1 1
6 1 1 3 1 NA NA NA NA
CMtmar5 CMtmar6 CMtmar7 CMtmar8 CMtmar9 CMtmar10 ChCoSupp ChMIncM ChMIncF
1 NA NA NA NA NA NA 3 1 NA
2 NA NA NA NA NA NA 3 2 NA
3 NA NA NA NA NA NA 2 2 NA
4 1 1 1 2 1 1 NA NA 1
5 1 1 1 2 1 1 NA NA 1
6 NA NA NA NA NA NA 3 8 NA
ChMCont RBGaran2 RBGGov DigPCUn DigPCctl DigPCcon DigPCrsk DigGVun DigGVctl
1 1 2 NA 2 2 2 1 NA NA
2 4 2 NA 2 3 3 1 NA NA
3 2 3 NA 3 3 3 8 NA NA
4 NA NA NA NA NA NA NA 1 2
5 NA NA NA NA NA NA NA 3 3
6 1 1 1 1 3 1 2 NA NA
DigGVcon DigGVrsk DigPro NHSSat WkHmNow WkHmJan CovWkc CovNoWkc CovWkr1
1 NA NA 2 3 NA NA NA NA NA
2 NA NA 2 2 NA NA NA NA NA
3 NA NA 2 3 NA NA NA NA NA
4 4 1 2 2 1 2 NA 1 0
5 3 8 1 2 3 3 1 NA 0
6 NA NA 2 2 NA NA NA NA NA
CovWkr2 CovWkr3 CovWkr4 CovWkr5 CovWkr6 CovWk1 CovWk2 CovWk3 GovtWork
1 NA NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA NA NA
4 0 0 0 1 0 5 5 5 NA
5 0 0 0 0 1 3 3 3 NA
6 NA NA NA NA NA NA NA NA NA
GovTrust CLRTRUST MPsTrust LoseTch VoteIntr PtyNMat2 PolPart01 PolPart02
1 NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA NA
4 NA NA NA NA NA NA NA NA
5 NA NA NA NA NA NA NA NA
6 NA NA NA NA NA NA NA NA
PolPart03 PolPart04 PolPart05 PolPart06 PolPart07 PolPart08 PolPart09
1 NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA
4 NA NA NA NA NA NA NA
5 NA NA NA NA NA NA NA
6 NA NA NA NA NA NA NA
PolPart10 PolPart11 REFHANG RefSyst UnempJob SocHelp DoleFidl WelfFeet
1 NA NA NA NA 3 4 4 4
2 NA NA NA NA 3 3 3 4
3 NA NA NA NA 3 4 4 4
4 NA NA NA NA 2 3 3 1
5 NA NA NA NA 2 4 2 3
6 NA NA NA NA 2 2 2 2
welfhelp morewelf damlives proudwlf Redistrb BigBusnN Wealth RichLaw Indust4
1 4 2 2 1 3 4 3 5 4
2 4 3 1 2 4 3 3 4 4
3 3 3 1 1 3 3 2 3 3
4 2 4 3 3 4 2 2 2 3
5 3 3 3 2 4 2 3 3 4
6 3 3 4 2 4 4 3 5 4
TradVals StifSent DeathApp Obey WrongLaw Censor NatIdGB ChAttend DisNew2
1 3 3 2 3 4 3 5 7 2
2 4 3 2 2 3 2 6 NA 2
3 3 3 3 2 2 2 1 NA 2
4 2 1 2 1 2 2 3 7 2
5 4 3 3 3 4 2 3 NA 2
6 1 2 3 1 3 2 3 1 2
DisAct HEdQual2 HhldEdu EURefV2 EUVOTWHO EURefb Voted Vote Anybn3 HHincome
1 NA 2 2 NA NA NA 2 NA 1 2
2 NA 1 NA NA NA NA 1 2 2 3
3 NA 2 1 NA NA NA 1 2 2 3
4 NA 4 2 NA NA NA 1 1 1 4
5 NA 3 2 NA NA NA 1 1 1 3
6 NA 1 NA NA NA NA 1 1 1 9
Maininc5 REarn HIncDif4 RetExp RetExpb FutrWrk PenKnow2 PenExp2 PenComp
1 4 NA 3 NA NA NA NA NA NA
2 2 NA 2 NA NA NA NA NA NA
3 2 NA 2 NA NA NA NA NA NA
4 1 3 2 3 60 2 1 7000 4
5 1 3 3 3 65 1 2 130 2
6 1 NA 3 NA NA NA NA NA NA
PenIntr INFORET3 WkPKnw WKPSav WkPSpn WPSvUs WPSvWw WPSvEas PrPKnw PrPSav
1 NA NA NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA NA NA
3 NA NA NA NA NA NA NA NA NA NA
4 2 2 2 1 4 1 1 1 NA NA
5 2 2 3 1 4 1 2 2 NA NA
6 NA NA NA NA NA NA NA NA NA NA
PrPSpn PrPSvUs PrPSvWW PrPSvEas NCOutcome Ragecat Ragecat20 DisActDV leftrigh
1 NA NA NA NA 1 7 6 3 3.8
2 NA NA NA NA 1 7 6 3 3.6
3 NA NA NA NA 1 6 5 3 2.8
4 NA NA NA NA 1 3 3 3 2.6
5 NA NA NA NA 1 3 3 3 3.2
6 NA NA NA NA 1 7 7 3 4.0
libauth welfare2 libauth2 leftrig2 welfgrp REconAct20 REconSum20 RaceOri4
1 3.000000 2.000 2 3 1 9 6 3
2 3.333333 2.375 2 3 1 9 6 3
3 3.500000 2.125 2 2 1 9 6 3
4 4.333333 3.625 3 2 3 3 2 3
5 2.833333 3.000 2 2 2 3 2 3
6 4.000000 3.500 3 3 2 9 6 3
LegMarStE HhlAdGpd HhlChlGpd BestNatU2 RetirAg3 ReligSum20 RlFamSum20
1 4 1 0 1 65 3 1
2 1 2 0 3 58 5 2
3 1 2 0 1 54 5 1
4 1 2 1 1 NA 3 2
5 1 2 1 2 NA 5 3
6 1 2 0 2 99 3 3
EmplStatDV RClassGP serialh GOR gor2 BSA20_wt_new
1 4 1 321100002 1 1 0.7099859
2 6 1 321100014 1 1 0.3145871
3 7 1 321100014 1 1 0.5649618
4 4 1 321100040 1 1 0.9355446
5 7 2 321100040 1 1 0.6830794
6 3 1 321100042 1 1 1.4006989</code></pre>
</div>
</div>
<p><strong>Questions</strong></p>
<ol type="1">
<li>What is the overall sample size?</li>
<li>How many variables are there in the dataset?</li>
</ol>
<p>Now, focus on the three variables we will use.</p>
<p><strong>Note</strong> In traditional statistical software packages such as SPSS or Stata, categorical variables are coded as arbitrary numbers, to which values labels are attached that describe the substantive meaning of these values. R on the other hand can either directly deal with the value themselves as alphanumeric variables, or with its own version of categorical variables, known as ‘factors’. There aren’t straightforward ways to convert SPSS or Stata labelled categorical variables into R factors. The approach followed by the <code>Haven</code> package that we use here consist in preserving the original numeric values in the data, and add attributes that can be manipulated separately. Attributes are a special type of R objects that have a name, and can be read using the <code>attr()</code> function. Each variable has a ‘label’ and ‘labels’ attribute. The former is the variable description, the latter the value labels. Alternatively, haven-imported numeric variables can be converted into factors with levels (ie categories) reflecting the SPSS or Stata value labels, but with numeric values different from the original ones.</p>
<p>Let’s examine the original variable description and value labels.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb8"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="co"># We can do this variable by variable...</span></span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="fu">attr</span>(bsa20<span class="sc">$</span>TAXSPEND,<span class="st">"label"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "If it had to choose, should govt reduce/increase/maintain levels of taxation and spending?"</code></pre>
</div>
<div class="sourceCode cell-code" id="cb10"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Or all as once</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="fu">t</span>(bsa20<span class="sc">|></span><span class="fu">select</span>(TAXSPEND,EUVOTWHO,PenExp2)</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a> <span class="sc">|></span><span class="fu">summarise_all</span>(attr,<span class="st">"label"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> [,1]
TAXSPEND "If it had to choose, should govt reduce/increase/maintain levels of taxation and spending?"
EUVOTWHO "Did you vote to 'remain a member of the EU' or to 'leave the EU'?"
PenExp2 "How much do you think someone who reaches State Pension age today would receive in pounds per week?"</code></pre>
</div>
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="co"># The same holds with value labels</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="fu">attr</span>(bsa20<span class="sc">$</span>TAXSPEND,<span class="st">"labels"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> Not applicable
-1
Reduce taxes and spend less on health, education and social benefits
1
Keep taxes and spending on these services at the same level as now
2
Increase taxes and spend more on health, education and social benefits
3
Don't know
8
Prefer not to answer
9 </code></pre>
</div>
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a><span class="fu">attr</span>(bsa20<span class="sc">$</span>EUVOTWHO,<span class="st">"labels"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> Not applicable Remain a member of the European Union
-1 1
Leave the European Union I Don't remember
2 3
Don't know Prefer not to answer
8 9 </code></pre>
</div>
</div>
<p><strong>Question 3</strong> What do the variables measure and how?</p>
</section>
<section id="missing-values" class="level3">
<h3 class="anchored" data-anchor-id="missing-values">2. Missing values</h3>
<p>Let’s now examine the distribution of our three variables. We can temporarily convert <code>EUVOTWHO</code> and <code>TAXSPEND</code> into factors using <code>mutate()</code> for a more meaningful output that include their value labels. Review the frequency tables, examining the ‘not applicable’ and ‘don’t know’ categories.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>bsa20<span class="sc">%>%</span><span class="fu">select</span>(EUVOTWHO,TAXSPEND) <span class="sc">%>%</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="fu">as_factor</span>(.)) <span class="sc">%>%</span></span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">summary</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> EUVOTWHO
Not applicable : 0
Remain a member of the European Union: 635
Leave the European Union : 463
I Don't remember : 2
Don't know : 0
Prefer not to answer : 21
NA's :2843
TAXSPEND
Not applicable : 0
Reduce taxes and spend less on health, education and social benefits : 186
Keep taxes and spending on these services at the same level as now :1589
Increase taxes and spend more on health, education and social benefits:2133
Don't know : 35
Prefer not to answer : 21
</code></pre>
</div>
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="fu">summary</span>(bsa20<span class="sc">$</span>PenExp2)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
0 120 160 1293 200 9999 1076 </code></pre>
</div>
</div>
<p><strong>Question 4</strong> Why for EUVOTWHO and PenExp2 are there so many system missing values (NA)? Note, you can use the documentation to check if needed. What does this mean when it comes to interpreting the percentages?</p>
<p>When analysing survey data, it is sometimes convenient to set all item nonresponses such as ´Don’t know´ and ‘Prefer not to say’ as system missing so that they do not appear in the results. However, the BSA treated ‘don’t know’ and refusals as valid responses when weights were computed. Therefore with the BSA, we can convert item non response to system missing as along as we are not planning to use the data to make inference about the British population, otherwise we might get biased results.</p>
<p>For the record, the code below show how to recode the missing values into system missing (NA) using separate variables. For ease of interpretation, we also convert the original numeric variable into labelled factors using <code>as_factor()</code>, so that they directly display the value labels.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>bsa20<span class="ot"><-</span>bsa20<span class="sc">%>%</span><span class="fu">mutate</span>(</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a> <span class="at">TAXSPEND.r=</span><span class="fu">factor</span>(<span class="fu">as_factor</span>(TAXSPEND,<span class="st">"labels"</span>), </span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a> <span class="at">exclude =</span> <span class="fu">c</span>(<span class="st">"Prefer not to answer"</span>,</span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a> <span class="st">"Don't know"</span>)),</span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a> <span class="at">EUVOTWHO.r=</span><span class="fu">factor</span>(<span class="fu">as_factor</span>(EUVOTWHO,<span class="st">"labels"</span>),</span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a> <span class="at">exclude =</span> <span class="fu">c</span>(<span class="st">"Prefer not to answer"</span>,</span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a> <span class="st">"I Don't remember"</span>,<span class="st">"Not applicable"</span>,<span class="cn">NA</span>)),</span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a> <span class="at">PenExp2.r=</span><span class="fu">ifelse</span>(PenExp2<span class="sc">==-</span><span class="dv">1</span> <span class="sc">|</span> PenExp2<span class="sc">>=</span><span class="dv">9998</span>,<span class="cn">NA</span>,PenExp2)</span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true" tabindex="-1"></a><span class="do">### Value labels need to be truncated as they are rather lengthy!</span></span>
<span id="cb20-11"><a href="#cb20-11" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(bsa20<span class="sc">$</span>TAXSPEND.r)<span class="ot"><-</span><span class="fu">substr</span>(<span class="fu">levels</span>(bsa20<span class="sc">$</span>TAXSPEND.r),<span class="dv">1</span>,<span class="dv">14</span>)</span>
<span id="cb20-12"><a href="#cb20-12" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(bsa20<span class="sc">$</span>EUVOTWHO.r)<span class="ot"><-</span><span class="fu">substr</span>(<span class="fu">levels</span>(bsa20<span class="sc">$</span>EUVOTWHO.r),<span class="dv">1</span>,<span class="dv">6</span>)</span>
<span id="cb20-13"><a href="#cb20-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-14"><a href="#cb20-14" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(bsa20<span class="sc">$</span>TAXSPEND.r)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "Reduce taxes a" "Keep taxes and" "Increase taxes"</code></pre>
</div>
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(bsa20<span class="sc">$</span>EUVOTWHO.r)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "Remain" "Leave "</code></pre>
</div>
</div>
</section>
<section id="compare-unweighted-and-weighted-proportions" class="level3">
<h3 class="anchored" data-anchor-id="compare-unweighted-and-weighted-proportions">3. Compare unweighted and weighted proportions</h3>
<p>Let’s examine the unweighted responses first. In order to ensure coherence with the remainder of this exercise, we use <code>xtabs()</code> for categorical variables and <code>summary()</code> for continuous ones.</p>
<p>Unlike some other surveys, the BSA has retained observations with “Don’t knows” and ‘Does not apply’ when weights were computed. As a result, any univariate analysis aiming to make inference about the British population needs to retain these observations, otherwise the estimated results might be incorrect. As a result the code below retains them.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a>bsa20<span class="ot"><-</span>bsa20<span class="sc">%>%</span><span class="fu">mutate</span>(</span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a> <span class="at">TAXSPEND.f=</span><span class="fu">as_factor</span>(TAXSPEND,<span class="st">"labels"</span>), </span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a> <span class="at">EUVOTWHO.f=</span><span class="fu">as_factor</span>(EUVOTWHO,<span class="st">"labels"</span>),</span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a> <span class="at">PenExp2.=</span><span class="fu">ifelse</span>(PenExp2<span class="sc">==-</span><span class="dv">1</span> <span class="sc">|</span> PenExp2<span class="sc">>=</span><span class="dv">9998</span>,<span class="cn">NA</span>,PenExp2)</span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a><span class="co"># As before, we can truncate factor levels for a more human-friendly output</span></span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(bsa20<span class="sc">$</span>TAXSPEND.f)<span class="ot"><-</span><span class="fu">substr</span>(<span class="fu">levels</span>(bsa20<span class="sc">$</span>TAXSPEND.f),<span class="dv">1</span>,<span class="dv">14</span>)</span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a><span class="fu">levels</span>(bsa20<span class="sc">$</span>EUVOTWHO.f)<span class="ot"><-</span><span class="fu">substr</span>(<span class="fu">levels</span>(bsa20<span class="sc">$</span>EUVOTWHO.f),<span class="dv">1</span>,<span class="dv">6</span>)</span>
<span id="cb24-10"><a href="#cb24-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-11"><a href="#cb24-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-12"><a href="#cb24-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-13"><a href="#cb24-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-14"><a href="#cb24-14" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>( <span class="do">### Rounds the results to one decimal</span></span>
<span id="cb24-15"><a href="#cb24-15" aria-hidden="true" tabindex="-1"></a> <span class="dv">100</span><span class="sc">*</span> <span class="do">### Converts proportions to % </span></span>
<span id="cb24-16"><a href="#cb24-16" aria-hidden="true" tabindex="-1"></a> <span class="fu">prop.table</span>( <span class="do">### Computes proportions</span></span>
<span id="cb24-17"><a href="#cb24-17" aria-hidden="true" tabindex="-1"></a> <span class="fu">xtabs</span>(<span class="sc">~</span>TAXSPEND.f,bsa20, <span class="do">### Computes frequencies,</span></span>
<span id="cb24-18"><a href="#cb24-18" aria-hidden="true" tabindex="-1"></a> <span class="at">drop.unused.levels =</span> T) <span class="do">### Leaves out levels with 0 observations),</span></span>
<span id="cb24-19"><a href="#cb24-19" aria-hidden="true" tabindex="-1"></a> ), </span>
<span id="cb24-20"><a href="#cb24-20" aria-hidden="true" tabindex="-1"></a> <span class="dv">1</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>TAXSPEND.f
Reduce taxes a Keep taxes and Increase taxes Don't know Prefer not to
4.7 40.1 53.8 0.9 0.5 </code></pre>
</div>
<div class="sourceCode cell-code" id="cb26"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(<span class="dv">100</span><span class="sc">*</span><span class="fu">prop.table</span>(<span class="fu">xtabs</span>(<span class="sc">~</span>EUVOTWHO.f,bsa20,<span class="at">drop.unused.levels =</span> T)),<span class="dv">1</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>EUVOTWHO.f
Remain Leave I Don' Prefer
56.6 41.3 0.2 1.9 </code></pre>
</div>
<div class="sourceCode cell-code" id="cb28"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="fu">summary</span>(bsa20<span class="sc">$</span>PenExp2)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
0 120 160 1293 200 9999 1076 </code></pre>
</div>
</div>
<p>What is the (unweighted) percentage of respondents who say they voted remain in the EU referendum? About 58 percent of sample members who voted in referendum said they voted to remain. This figure seems a bit high (though people do not always report accurately).</p>
<p>Let’s compare with the weighted frequencies. We will use the <code>wtd.table()</code> from the <code>Hmisc</code> package. The weights are specified after the variable for which we request the frequencies in the command below.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb30"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Raw output</span></span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a><span class="fu">wtd.table</span>(bsa20<span class="sc">$</span>EUVOTWHO.f,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>$x
[1] "Remain" "Leave" "I Don'" "Prefer"
$sum.of.weights
[1] 565.011079 489.146642 3.752765 22.527320</code></pre>
</div>
<div class="sourceCode cell-code" id="cb32"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Converted into proportions </span></span>
<span id="cb32-2"><a href="#cb32-2" aria-hidden="true" tabindex="-1"></a>euv.w<span class="ot"><-</span><span class="fu">wtd.table</span>(bsa20<span class="sc">$</span>EUVOTWHO.f,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)</span>
<span id="cb32-3"><a href="#cb32-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb32-4"><a href="#cb32-4" aria-hidden="true" tabindex="-1"></a><span class="co"># Raw results</span></span>
<span id="cb32-5"><a href="#cb32-5" aria-hidden="true" tabindex="-1"></a>euv.wp<span class="ot"><-</span><span class="fu">round</span>(</span>
<span id="cb32-6"><a href="#cb32-6" aria-hidden="true" tabindex="-1"></a> <span class="dv">100</span><span class="sc">*</span></span>
<span id="cb32-7"><a href="#cb32-7" aria-hidden="true" tabindex="-1"></a> <span class="fu">prop.table</span>(</span>
<span id="cb32-8"><a href="#cb32-8" aria-hidden="true" tabindex="-1"></a> euv.w<span class="sc">$</span>sum.of.weights),</span>
<span id="cb32-9"><a href="#cb32-9" aria-hidden="true" tabindex="-1"></a> <span class="dv">1</span>)</span>
<span id="cb32-10"><a href="#cb32-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb32-11"><a href="#cb32-11" aria-hidden="true" tabindex="-1"></a>euv.wp</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 52.3 45.3 0.3 2.1</code></pre>
</div>
<div class="sourceCode cell-code" id="cb34"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb34-1"><a href="#cb34-1" aria-hidden="true" tabindex="-1"></a><span class="co"># We can easily improve the output</span></span>
<span id="cb34-2"><a href="#cb34-2" aria-hidden="true" tabindex="-1"></a><span class="fu">cbind</span>(euv.w<span class="sc">$</span>x,<span class="st">"Weighted %"</span><span class="ot">=</span>euv.wp)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> Weighted %
[1,] "Remain" "52.3"
[2,] "Leave" "45.3"
[3,] "I Don'" "0.3"
[4,] "Prefer" "2.1" </code></pre>
</div>
</div>
<p>Now, what proportion say they voted remain in the EU referendum? It is about 52 percent, lower than the unweighted proportion and closer to the actual referendum results. Do you have an idea as to why this might be the case?</p>
</section>
<section id="confidence-intervals" class="level3">
<h3 class="anchored" data-anchor-id="confidence-intervals">4. Confidence intervals</h3>
<p>So far, we have just computed point estimates without worrying about their precision. Estimates precision (or uncertainty) does matter insofar as it determines how big the ranges within which ‘true’ population values are likely to be. These are also known as the <em>confidence intervals</em> of our estimates.</p>
<p>In this exercise, we will be computing confidence intervals ’by hand‘ and ignore the survey design (ie whether clustering or stratification were used when collecting the sample) as the information is not available in this edition of the BSA. This amounts to assuming that the sample was collected using simple random sampling - which wasn’t the case - and increase the bias of our estimates.</p>
<p>In this exercise, we will be computing confidence intervals ’by hand‘ and ignore the survey design (ie whether clustering or stratification were used when collecting the sample) as the information is not available in this edition of the BSA. This amounts to assuming that the sample was collected using simple random sampling - which wasn’t the case - and increase the bias of our estimates.</p>
<p>We will explore the more reliable survey design functions provided by the <code>survey</code> package in the next exercise.</p>
<p>The <code>Hmisc</code> package provides <code>binconf()</code> a handy function to compute confidence intervals for proportions. Although this is usually left under the hood by traditional statistical packages, estimating confidence intervals for proportions of categorical variables necessitates looking at each one of them individually. In other words, we need to compute one set of confidence interval for each one of the categories of <code>TAXSPEND.f</code> and <code>EUVOTWHO.f</code> separately. We can then gather them into a table of results using <code>rbind()</code>.</p>
<p>We need to provide <code>binconf()</code> with two parameters: the frequencies for which we would like a confidence interval, and the total number of non missing observations.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb36"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb36-1"><a href="#cb36-1" aria-hidden="true" tabindex="-1"></a><span class="do">### Raw confidence interval for EUVOTWHO, unweighted</span></span>
<span id="cb36-2"><a href="#cb36-2" aria-hidden="true" tabindex="-1"></a><span class="fu">binconf</span>(<span class="fu">table</span>(bsa20<span class="sc">$</span>EUVOTWHO.f<span class="sc">==</span><span class="st">"Remain"</span>),<span class="fu">sum</span>(<span class="sc">!</span><span class="fu">is.na</span>(bsa20<span class="sc">$</span>EUVOTWHO.r)))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> PointEst Lower Upper
0.4426230 0.4134945 0.4721515
0.5783242 0.5488915 0.6072108</code></pre>
</div>
<div class="sourceCode cell-code" id="cb38"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb38-1"><a href="#cb38-1" aria-hidden="true" tabindex="-1"></a><span class="do">### We can convert the output into rounded percentages for better readability.</span></span>
<span id="cb38-2"><a href="#cb38-2" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(<span class="dv">100</span><span class="sc">*</span></span>
<span id="cb38-3"><a href="#cb38-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">binconf</span>(<span class="fu">table</span>(bsa20<span class="sc">$</span>EUVOTWHO.f<span class="sc">==</span><span class="st">"Remain"</span>),<span class="fu">sum</span>(<span class="sc">!</span><span class="fu">is.na</span>(bsa20<span class="sc">$</span>EUVOTWHO.f)))[<span class="dv">1</span>,],</span>
<span id="cb38-4"><a href="#cb38-4" aria-hidden="true" tabindex="-1"></a> <span class="dv">1</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>PointEst Lower Upper
43.4 40.5 46.3 </code></pre>
</div>
</div>
<p>We can adapt the syntax above to make it work with weighted frequencies:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb40"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb40-1"><a href="#cb40-1" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(<span class="dv">100</span><span class="sc">*</span></span>
<span id="cb40-2"><a href="#cb40-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">binconf</span>(<span class="fu">wtd.table</span>(bsa20<span class="sc">$</span>EUVOTWHO.f,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)<span class="sc">$</span>sum.of.weights[<span class="dv">2</span>],</span>
<span id="cb40-3"><a href="#cb40-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">sum</span>(<span class="fu">wtd.table</span>(bsa20<span class="sc">$</span>EUVOTWHO.f,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)<span class="sc">$</span>sum.of.weights)),</span>
<span id="cb40-4"><a href="#cb40-4" aria-hidden="true" tabindex="-1"></a> <span class="dv">1</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> PointEst Lower Upper
45.3 42.3 48.3</code></pre>
</div>
</div>
<p>What are the differences between weighted and unweighted confidence intervals for the proportion of people who voted remain?</p>
<p>Let us now do the same with people’s views about government tax and spending.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb42"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb42-1"><a href="#cb42-1" aria-hidden="true" tabindex="-1"></a>w.n<span class="ot"><-</span><span class="fu">sum</span>(<span class="fu">wtd.table</span>(bsa20<span class="sc">$</span>TAXSPEND.f,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)<span class="sc">$</span>sum.of.weights)</span>
<span id="cb42-2"><a href="#cb42-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb42-3"><a href="#cb42-3" aria-hidden="true" tabindex="-1"></a>ciprop<span class="ot"><-</span><span class="fu">cbind</span>(<span class="fu">levels</span>(bsa20<span class="sc">$</span>TAXSPEND.f),</span>
<span id="cb42-4"><a href="#cb42-4" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(<span class="dv">100</span><span class="sc">*</span></span>
<span id="cb42-5"><a href="#cb42-5" aria-hidden="true" tabindex="-1"></a><span class="fu">binconf</span>(<span class="fu">wtd.table</span>(bsa20<span class="sc">$</span>TAXSPEND.f,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)<span class="sc">$</span>sum.of.weights,w.n),</span>
<span id="cb42-6"><a href="#cb42-6" aria-hidden="true" tabindex="-1"></a><span class="dv">1</span>)</span>
<span id="cb42-7"><a href="#cb42-7" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb42-8"><a href="#cb42-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb42-9"><a href="#cb42-9" aria-hidden="true" tabindex="-1"></a>ciprop</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code> PointEst Lower Upper
"Not applicable" "5.5" "4.8" "6.3"
"Reduce taxes a" "42.8" "41.3" "44.3"
"Keep taxes and" "50.3" "48.8" "51.9"
"Increase taxes" "0.9" "0.6" "1.2"
"Don't know" "0.5" "0.3" "0.8" </code></pre>
</div>
</div>
<p>When computing confidence intervals for means, two steps are usually needed, whether embedded in a single line of code or not: compute the mean (or any other estimate), then the confidence interval itself using <code>confint</code>. We also use the <code>round()</code> function in order to remove unneeded decimal values.</p>
<p><strong>Question 5.</strong> What proportion think government should increase taxes and spend more on health, education and social benefits?</p>
<p>Several R packages offer functions for computing confidence intervals and standard errors of means. Here again, we privilege doing things by hand in order to properly undertstand what is happening in the background.</p>
<p>Under assumptions of simple random sampling, a 95% confidence of the mean is defined as plus or minus 1.96 times the standard error of the mean. The standard error of the mean itself is the standard error of the mean (that is, the square root of its variance) divided by the square of the sample size. Since we have functions for computing weighted means and variance in R, we can compute:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb44"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb44-1"><a href="#cb44-1" aria-hidden="true" tabindex="-1"></a>m.p<span class="ot"><-</span><span class="fu">wtd.mean</span>(bsa20<span class="sc">$</span>PenExp2.r,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new)</span>
<span id="cb44-2"><a href="#cb44-2" aria-hidden="true" tabindex="-1"></a>se.p<span class="ot"><-</span><span class="fu">sqrt</span>(<span class="fu">wtd.var</span>(bsa20<span class="sc">$</span>PenExp2.r,<span class="at">weights=</span>bsa20<span class="sc">$</span>BSA20_wt_new))</span>
<span id="cb44-3"><a href="#cb44-3" aria-hidden="true" tabindex="-1"></a>n<span class="ot"><-</span><span class="fu">sum</span>(bsa20<span class="sc">$</span>BSA20_wt_new[<span class="sc">!</span><span class="fu">is.na</span>(bsa20<span class="sc">$</span>PenExp2)])</span>
<span id="cb44-4"><a href="#cb44-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb44-5"><a href="#cb44-5" aria-hidden="true" tabindex="-1"></a>ci<span class="ot"><-</span><span class="fu">c</span>(m.p,m.p<span class="fl">-1.96</span><span class="sc">*</span>(se.p<span class="sc">/</span><span class="fu">sqrt</span>(n)),m.p<span class="fl">+1.96</span><span class="sc">*</span>(se.p<span class="sc">/</span><span class="fu">sqrt</span>(n)))</span>
<span id="cb44-6"><a href="#cb44-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb44-7"><a href="#cb44-7" aria-hidden="true" tabindex="-1"></a><span class="fu">round</span>(ci,<span class="dv">1</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 177.4 170.5 184.4</code></pre>
</div>
</div>
<p><strong>Question 6</strong> How much do people think they will get at state pension age?</p>
</section>
<section id="answers" class="level3">
<h3 class="anchored" data-anchor-id="answers">Answers</h3>
<ol type="1">
<li><p>There are 3964 cases in the dataset.</p></li>
<li><p>The total number of variables is 216.</p></li>
<li><p><em><code>TAXSPEND</code> records responses to the questions of whether government should reduce/increase/maintain levels of taxation and spending. There are three possible responses to the question.</em> <code>EUVOTWHO</code> records responses to the question ‘Did you vote to ’remain a member of the EU’ or to ‘leave the EU’?’ The responses are ‘Remain’ or ‘Leave’. *<code>PenExp2</code> contains responses to the question ‘How much do you think someone who reaches State Pension age today would receive in pounds per week?’ Responses are numeric.</p></li>
<li><p>There are two reasons for the many not applicable.</p></li>
</ol>
<ul>
<li>Routing: the question is only asked to those who said yes to a previous question (EURefV2).</li>
<li>Versions 5 and 6 - The BSA uses a split sample and the question is only asked in Versions 5 and 6.</li>
</ul>
<ol start="5" type="1">
<li><p>Between 48.8 and 51.9% in the population say the government should increase taxes and spend more.</p></li>
<li><p>The amount people think they will get at state pension age varies between £170 and £184, with an average (ie mean) in the region of £177.</p></li>
</ol>
</section>
</main>
<!-- /main column -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const clipboard = new window.ClipboardJS('.code-copy-button', {
text: function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
});
clipboard.on('success', function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
});
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
// TODO in 1.5, we should make sure this works without a callout special case
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}