-
Notifications
You must be signed in to change notification settings - Fork 3
/
p-050-business-logic.html
1128 lines (1046 loc) · 39.6 KB
/
p-050-business-logic.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>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>p-050-business-logic.knit</title>
<script src="site_libs/header-attrs-2.11/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="site_libs/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="textbook.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
</head>
<body>
<div class="container-fluid main-container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">DATA SCIENCE I</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://ds4ps.org/dp4ss/">
<span class="fa fa-university fa-2x"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
</div>
<div id="TOC">
<ul>
<li><a href="#constructing-groups" id="toc-constructing-groups"><span class="toc-section-number">1</span> Constructing Groups</a>
<ul>
<li><a href="#key-concepts" id="toc-key-concepts"><span class="toc-section-number">1.1</span> Key Concepts</a></li>
<li><a href="#logical-operators" id="toc-logical-operators"><span class="toc-section-number">1.2</span> Logical Operators</a></li>
<li><a href="#selector-vectors" id="toc-selector-vectors"><span class="toc-section-number">1.3</span> Selector Vectors</a></li>
<li><a href="#usefulness-of-selector-vectors" id="toc-usefulness-of-selector-vectors"><span class="toc-section-number">1.4</span> Usefulness of Selector Vectors</a></li>
</ul></li>
<li><a href="#subsets" id="toc-subsets"><span class="toc-section-number">2</span> Subsets</a>
<ul>
<li><a href="#compound-logical-statements" id="toc-compound-logical-statements"><span class="toc-section-number">2.1</span> Compound Logical Statements</a></li>
<li><a href="#the-opposite-of-operator" id="toc-the-opposite-of-operator"><span class="toc-section-number">2.2</span> The Opposite-Of Operator</a></li>
</ul></li>
<li><a href="#care-with-logical-statements" id="toc-care-with-logical-statements"><span class="toc-section-number">3</span> Care With Logical Statements</a></li>
<li><a href="#advanced-operations-with-logical-vectors" id="toc-advanced-operations-with-logical-vectors"><span class="toc-section-number">4</span> Advanced Operations with Logical Vectors</a>
<ul>
<li><a href="#find-and-replace" id="toc-find-and-replace"><span class="toc-section-number">4.1</span> Find and Replace</a></li>
<li><a href="#nas-in-logical-statements" id="toc-nas-in-logical-statements"><span class="toc-section-number">4.2</span> NAs in Logical Statements</a></li>
</ul></li>
<li><a href="#subsets-with-factors" id="toc-subsets-with-factors"><span class="toc-section-number">5</span> Subsets with Factors</a></li>
</ul>
</div>
<script src="https://cdn.datacamp.com/datacamp-light-latest.min.js"></script>
<script src="https://cdn.datacamp.com/datacamp-light-latest.min.js"></script>
<style>
th {
text-align: left;
}
td {
text-align: left;
}
</style>
<div id="constructing-groups" class="section level1" number="1">
<h1><span class="header-section-number">1</span> Constructing Groups</h1>
<div id="key-concepts" class="section level2 tip" number="1.1">
<h2><span class="header-section-number">1.1</span> Key Concepts</h2>
<p>We translate questions from plain English into computer code using <strong>logical statements</strong>.</p>
<p>Logical statements generate logical vectors or “selector vectors” where:</p>
<ul>
<li>TRUE signifies an observation belongs to our defined group</li>
<li>FALSE signifies an observation does not</li>
</ul>
<p>We use these vectors to:</p>
<ul>
<li>count group membership</li>
<li>determine the proportion of the population belonging to the group</li>
<li>create subsets of data belonging to the group</li>
</ul>
<p><br>
<br></p>
</div>
<p>Most data analysis require us to split our data into groups or segments so that we can look for trends or compare outcomes across various subpopulations.</p>
<p><br></p>
<blockquote>
<p>What percentage of women over 30 have graduate degrees?</p>
</blockquote>
<p><br></p>
<p>To be an effective data analyst we need to know how to translate a question from our native human language into phrases a computer will understand.</p>
<p><strong>Group of Interest:</strong></p>
<ul>
<li>female</li>
<li>age over 30</li>
<li>graduate degree</li>
</ul>
<p><strong>In R as a logical statement:</strong></p>
<pre class="r"><code>gender == "female" & age > 30 & grad.degree == TRUE</code></pre>
<p>Logical statements help us translate our research questions from human languages into computer code.</p>
<div class="figure"><span style="display:block;" id="fig:unnamed-chunk-3"></span>
<img src="figures/group_selection.png" alt="Logical statements define group membership" width="70%" />
<p class="caption">
Figure 1.1: Logical statements define group membership
</p>
</div>
<div id="logical-operators" class="section level2" number="1.2">
<h2><span class="header-section-number">1.2</span> Logical Operators</h2>
<p>Similar to mathematical operators, logical operators are a basic building block of data programming. Most often when working with data we are not creating complicated statistical models. We are identifying members of a group (print all of the females from the study), and describing a subset of the data (compare the average price of houses with a pool to houses without a pool).</p>
<p>In order to accomplish these simple tasks we need to use logic statements. A logic statement answers the question, does an observation belong to our group?</p>
<p>Many times groups are simple: identify all professions that have average salaries over $100k a year, for example.</p>
<p>Groups can be complex: identify the African American children from a specific zip code in Chicago that live in households with single mothers.</p>
<p>In this chapter we will use nine basic logical operators:</p>
<table>
<thead>
<tr class="header">
<th>Operator</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong><</strong></td>
<td>less than</td>
</tr>
<tr class="even">
<td><strong><=</strong></td>
<td>less than or equal to</td>
</tr>
<tr class="odd">
<td><strong>></strong></td>
<td>greater than</td>
</tr>
<tr class="even">
<td><strong>>=</strong></td>
<td>greater than or equal to</td>
</tr>
<tr class="odd">
<td><strong>==</strong></td>
<td>exactly equal to</td>
</tr>
<tr class="even">
<td><strong>!=</strong></td>
<td>not equal to</td>
</tr>
<tr class="odd">
<td><strong>x | y</strong></td>
<td>x OR y</td>
</tr>
<tr class="even">
<td><strong>x & y</strong></td>
<td>x AND y</td>
</tr>
<tr class="odd">
<td><strong>!</strong></td>
<td>opposite of</td>
</tr>
<tr class="even">
<td><strong>[ ]</strong></td>
<td>subset</td>
</tr>
</tbody>
</table>
<p>Logical operators create logical vectors, a vector that contains only TRUE or FALSE. The TRUE means that the observation belongs to a group, FALSE means it does not.</p>
<pre class="r"><code>x1 <- c( 7, 9, 1, 2 )
x1 > 5</code></pre>
<p><em>TRUE</em>, <em>TRUE</em>, <em>FALSE</em> and <em>FALSE</em></p>
<pre class="r"><code>gender <- c("male","male","female","female")
gender == "female"</code></pre>
<p><em>FALSE</em>, <em>FALSE</em>, <em>TRUE</em> and <em>TRUE</em></p>
<p><br>
<br></p>
<div class="question">
<p>Try it yourself:</p>
</div>
<div data-datacamp-exercise="" data-height="300" data-encoded="true">
eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiJ4MSA8LSBjKCA3LCA5LCAxLCAyIClcbiMgd2hhdCB3aWxsIHRoZSByZXR1cm4gdmVjdG9yIGJlIGZvciBlYWNoP1xueDEgPiA3XG54MSA+PSA3XG54MSA9PSA5IHwgeDEgPT0gMVxuXG5cbmdlbmRlciA8LSBjKFwibWFsZVwiLFwibWFsZVwiLFwiZmVtYWxlXCIsXCJmZW1hbGVcIilcbiMgd2hhdCB3aWxsIHRoZSByZXR1cm4gdmVjdG9yIGJlIGZvciBlYWNoP1xuZ2VuZGVyID09IFwiZmVtYWxlXCJcbmdlbmRlciAhPSBcImZlbWFsZVwiXG5nZW5kZXIgPT0gXCJtYWxlXCJcbmdlbmRlciA9PSBcIk1BTEVcIiJ9
</div>
<p>Note that the logical statement for “equals” is written with two equal signs. This is important to remember, because using a single equal sign can introduce subtle errors into your analysis.</p>
<pre class="r"><code>x1 <- c( 7, 9, 1, 2 )
x1 == 9</code></pre>
<pre><code>## [1] FALSE TRUE FALSE FALSE</code></pre>
<pre class="r"><code>x1 = 9 # single equal overwrites your data
x1</code></pre>
<pre><code>## [1] 9</code></pre>
<p>We can write compound logical statements using the <strong>AND</strong> <code>&</code> and <strong>OR</strong> <code>|</code> operators:</p>
<table style="width:39%;">
<colgroup>
<col width="6%" />
<col width="12%" />
<col width="19%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">id</th>
<th align="center">gender</th>
<th align="center">study.group</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">1</td>
<td align="center">male</td>
<td align="center">treatment</td>
</tr>
<tr class="even">
<td align="center">2</td>
<td align="center">male</td>
<td align="center">control</td>
</tr>
<tr class="odd">
<td align="center">3</td>
<td align="center">female</td>
<td align="center">treatment</td>
</tr>
<tr class="even">
<td align="center">4</td>
<td align="center">female</td>
<td align="center">control</td>
</tr>
</tbody>
</table>
<pre class="r"><code>gender == "female" & study.group == "treatment"</code></pre>
<p><em>FALSE</em>, <em>FALSE</em>, <em>TRUE</em> and <em>FALSE</em></p>
<pre class="r"><code>gender == "female" | study.group == "treatment"</code></pre>
<p><em>TRUE</em>, <em>FALSE</em>, <em>TRUE</em> and <em>TRUE</em></p>
</div>
<div id="selector-vectors" class="section level2" number="1.3">
<h2><span class="header-section-number">1.3</span> Selector Vectors</h2>
<p>Note that we use operators to create logical vectors where TRUE designates observations that belong to the defined group, and FALSE designates observations outside the group. The term <strong>“selector vector”</strong> is a useful way to remember this purpose.</p>
<p>After you have defined a group by composing a logical statement, then the vector can be used to count group members and take subsets of other variables to calculate group statistics.</p>
<table style="width:54%;">
<colgroup>
<col width="12%" />
<col width="12%" />
<col width="13%" />
<col width="15%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">name</th>
<th align="center">gender</th>
<th align="center">group</th>
<th align="center">strength</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">frank</td>
<td align="center">male</td>
<td align="center">treat</td>
<td align="center">27</td>
</tr>
<tr class="even">
<td align="center">wanda</td>
<td align="center">female</td>
<td align="center">treat</td>
<td align="center">43</td>
</tr>
<tr class="odd">
<td align="center">sanjay</td>
<td align="center">male</td>
<td align="center">control</td>
<td align="center">19</td>
</tr>
<tr class="even">
<td align="center">nancy</td>
<td align="center">female</td>
<td align="center">control</td>
<td align="center">58</td>
</tr>
</tbody>
</table>
<pre class="r"><code>these.female <- dat$gender == "female"
sum( these.female ) # number of women in the study</code></pre>
<pre><code>## [1] 2</code></pre>
<pre class="r"><code>mean( these.female ) # proportion of the study that is women</code></pre>
<pre><code>## [1] 0.5</code></pre>
<pre class="r"><code>dat[ these.female , ] # all data belonging to women</code></pre>
<pre><code>## name gender group strength
## 2 wanda female treat 43
## 4 nancy female control 58</code></pre>
<pre class="r"><code>mean( dat$strength[ these.female ] ) # average outcome for women in the study</code></pre>
<pre><code>## [1] 50.5</code></pre>
<p>I will consistently name my logical vectors “these.GROUP” throughout the chapters, where GROUP represents the group label. For example, I selected women above, so the selector vector is called “these.female”.</p>
</div>
<div id="usefulness-of-selector-vectors" class="section level2" number="1.4">
<h2><span class="header-section-number">1.4</span> Usefulness of Selector Vectors</h2>
<p>Selector vectors, i.e. logical vectors that were created by defining a group, have three main uses in our analysis.</p>
<p><strong>ONE</strong>: Logical vectors give us an easy way to count things within defined groups.</p>
<p>We can apply a <strong>sum()</strong> function to a logical vector, and the result will be a tally of all of the TRUE cases. The <strong>mean()</strong> function will give us the proportion of the sample that belongs to our defined group.</p>
<pre class="r"><code># how many females do we have in our study?
sum( gender == "female" )</code></pre>
<pre><code>## [1] 2</code></pre>
<pre class="r"><code># how many females do we have in our treatment group?
sum( gender == "female" & group == "treat" )</code></pre>
<pre><code>## [1] 1</code></pre>
<pre class="r"><code># what proportion of our study are men?
mean( gender == "male" )</code></pre>
<pre><code>## [1] 0.5</code></pre>
<p><strong>TWO:</strong> We can create a selector variable that is used for subsets. A selector vector used in a subset operator will drop all observations that are FALSE, isolating data belonging to the group:</p>
<pre class="r"><code>these.female <- gender == "female"
name[ these.female ]</code></pre>
<pre><code>## [1] "wanda" "nancy"</code></pre>
<pre class="r"><code>strength[ these.female ]</code></pre>
<pre><code>## [1] 43 58</code></pre>
<p>Or we can create a subset of the full dataset:</p>
<pre class="r"><code>dat[ these.female , ]</code></pre>
<table style="width:65%;">
<colgroup>
<col width="12%" />
<col width="11%" />
<col width="12%" />
<col width="13%" />
<col width="15%" />
</colgroup>
<thead>
<tr class="header">
<th align="center"> </th>
<th align="center">name</th>
<th align="center">gender</th>
<th align="center">group</th>
<th align="center">strength</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center"><strong>2</strong></td>
<td align="center">wanda</td>
<td align="center">female</td>
<td align="center">treat</td>
<td align="center">43</td>
</tr>
<tr class="even">
<td align="center"><strong>4</strong></td>
<td align="center">nancy</td>
<td align="center">female</td>
<td align="center">control</td>
<td align="center">58</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="subsets" class="section level1" number="2">
<h1><span class="header-section-number">2</span> Subsets</h1>
<p>The subset operators <strong>[ ]</strong> are one of the most common you will use in R.</p>
<p>The primary rule of subsets is to use a data operator to create a logical selector vector, and use that to generate subsets. Any observation that corresponds to TRUE will be retained, any observation that corresponds to FALSE will be dropped.</p>
<p>Consider this data:</p>
<table style="width:54%;">
<colgroup>
<col width="12%" />
<col width="12%" />
<col width="13%" />
<col width="15%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">name</th>
<th align="center">gender</th>
<th align="center">group</th>
<th align="center">strength</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">frank</td>
<td align="center">male</td>
<td align="center">treat</td>
<td align="center">27</td>
</tr>
<tr class="even">
<td align="center">wanda</td>
<td align="center">female</td>
<td align="center">treat</td>
<td align="center">43</td>
</tr>
<tr class="odd">
<td align="center">sanjay</td>
<td align="center">male</td>
<td align="center">control</td>
<td align="center">19</td>
</tr>
<tr class="even">
<td align="center">nancy</td>
<td align="center">female</td>
<td align="center">control</td>
<td align="center">58</td>
</tr>
</tbody>
</table>
<p>Vectors are only one dimension (a single column), so you only provide one argument to the subset operator:</p>
<pre class="r"><code>these.treated <- dat$group == "treat"
name[ these.treated ]</code></pre>
<pre><code>## [1] "frank" "wanda"</code></pre>
<pre class="r"><code>strength[ these.treated ]</code></pre>
<pre><code>## [1] 27 43</code></pre>
<p>Data frames are two dimensions (rows and columns). Thus we need to provide two arguments to the subset operator, one to control which rows we select, and one to control which columns we select.</p>
<p>The two dimensions are seperated by a comma, and if you leave one blank it will not drop anything in the row or column.</p>
<blockquote>
<p><strong><code>dat[ ROW POSITION , COLUMN POSITION ]</code></strong></p>
</blockquote>
<pre class="r"><code>these.control <- dat$group == "control"
dat[ these.control , ] # all data in the control group</code></pre>
<pre><code>## name gender group strength
## 3 sanjay male control 19
## 4 nancy female control 58</code></pre>
<pre class="r"><code>dat[ , c("name","gender") ] # select two columns of data</code></pre>
<pre><code>## name gender
## 1 frank male
## 2 wanda female
## 3 sanjay male
## 4 nancy female</code></pre>
<pre class="r"><code># create a subset
dat.women <- dat[ dat$gender == "female" , ]
dat.women</code></pre>
<pre><code>## name gender group strength
## 2 wanda female treat 43
## 4 nancy female control 58</code></pre>
<div class="question">
<p>Specify the following desired selections from the table:</p>
<table style="width:54%;">
<colgroup>
<col width="12%" />
<col width="12%" />
<col width="13%" />
<col width="15%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">name</th>
<th align="center">gender</th>
<th align="center">group</th>
<th align="center">strength</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">frank</td>
<td align="center">male</td>
<td align="center">treat</td>
<td align="center">27</td>
</tr>
<tr class="even">
<td align="center">wanda</td>
<td align="center">female</td>
<td align="center">treat</td>
<td align="center">43</td>
</tr>
<tr class="odd">
<td align="center">sanjay</td>
<td align="center">male</td>
<td align="center">control</td>
<td align="center">19</td>
</tr>
<tr class="even">
<td align="center">nancy</td>
<td align="center">female</td>
<td align="center">control</td>
<td align="center">58</td>
</tr>
</tbody>
</table>
</div>
<div data-datacamp-exercise="" data-height="300" data-encoded="true">
eyJsYW5ndWFnZSI6InIiLCJwcmVfZXhlcmNpc2VfY29kZSI6Im5hbWUgPC0gYyhcImZyYW5rXCIsXCJ3YW5kYVwiLFwic2FuamF5XCIsXCJuYW5jeVwiKVxuZ3JvdXAgPC0gYyhcInRyZWF0XCIsXCJ0cmVhdFwiLFwiY29udHJvbFwiLFwiY29udHJvbFwiKVxuZ2VuZGVyIDwtIGMoXCJtYWxlXCIsXCJmZW1hbGVcIixcIm1hbGVcIixcImZlbWFsZVwiKVxuc3RyZW5ndGggPC0gYygyNyw0MywxOSw1OClcbmRhdCA8LSBkYXRhLmZyYW1lKCBuYW1lLCBnZW5kZXIsIGdyb3VwLCBzdHJlbmd0aCApIiwic2FtcGxlIjoiIyBhbGwgd29tZW5cbnRoZXNlLndvbWVuIDwtIGRhdCRnZW5kZXIgPT0gXCJmZW1hbGVcIlxuZGF0WyB0aGVzZS53b21lbiAsIF1cblxuIyBhbGwgd29tZW4gaW4gdGhlIGNvbnRyb2wgZ3JvdXBcblxuIyBldmVyeW9uZSB0aGF0IHNjb3JlZCBvdmVyIDIwIG9uIHRoZSBzdHJlbmd0aCB0ZXN0XG5cbiMgb25seSB0aGUgc3R1ZHkgZ3JvdXAgYW5kIHN0cmVuZ3RoIGNvbHVtbnMgZnJvbSB0aGUgZGF0YXNldCJ9
</div>
<div id="compound-logical-statements" class="section level2" number="2.1">
<h2><span class="header-section-number">2.1</span> Compound Logical Statements</h2>
<p>We can combine multiple logical statements using the AND, OR, and NOT operators ( &, |, ! ). This functionality gives us an incredible ability to specify very granular groups within our analysis. This will be important as we begin to construct analysis in a way that we search for apples to apples comparisons within our data in order to make inferences about program effectiveness.</p>
<p>These statements require some precision, however. Use care when applying the AND, OR, and NOT operators as to not include unintended data in your sample.</p>
</div>
<div id="the-opposite-of-operator" class="section level2" number="2.2">
<h2><span class="header-section-number">2.2</span> The Opposite-Of Operator</h2>
<p>The <strong>!</strong> operator is a special case, where it is not used to define a new logical vector, but rather it swaps the values of an existing logical vector.</p>
<pre class="r"><code>! TRUE</code></pre>
<pre><code>## [1] FALSE</code></pre>
<pre class="r"><code>! FALSE</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>x1 <- c(7,9,1,2)
these <- x1 > 5
these</code></pre>
<pre><code>## [1] TRUE TRUE FALSE FALSE</code></pre>
<pre class="r"><code>! these</code></pre>
<pre><code>## [1] FALSE FALSE TRUE TRUE</code></pre>
<p>Be careful with the order of operations though! If we are working with this data, for example:</p>
<table style="width:28%;">
<colgroup>
<col width="13%" />
<col width="13%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">group</th>
<th align="center">gender</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">treat</td>
<td align="center">male</td>
</tr>
<tr class="even">
<td align="center">treat</td>
<td align="center">female</td>
</tr>
<tr class="odd">
<td align="center">control</td>
<td align="center">male</td>
</tr>
<tr class="even">
<td align="center">control</td>
<td align="center">female</td>
</tr>
</tbody>
</table>
<p>And we define men in the treatment group:</p>
<pre class="r"><code>these <- group == "treat" & gender == "male"
dat[ these , ] %>% pander</code></pre>
<table style="width:24%;">
<colgroup>
<col width="11%" />
<col width="12%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">group</th>
<th align="center">gender</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">treat</td>
<td align="center">male</td>
</tr>
</tbody>
</table>
<p>Note that the opposite of men in the treatment group is <strong>NOT</strong> women in the control group:</p>
<pre class="r"><code>these <- ! ( group == "treat" & gender == "male" )
dat[ these , ] %>% pander</code></pre>
<table style="width:40%;">
<colgroup>
<col width="12%" />
<col width="13%" />
<col width="13%" />
</colgroup>
<thead>
<tr class="header">
<th align="center"> </th>
<th align="center">group</th>
<th align="center">gender</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center"><strong>2</strong></td>
<td align="center">treat</td>
<td align="center">female</td>
</tr>
<tr class="even">
<td align="center"><strong>3</strong></td>
<td align="center">control</td>
<td align="center">male</td>
</tr>
<tr class="odd">
<td align="center"><strong>4</strong></td>
<td align="center">control</td>
<td align="center">female</td>
</tr>
</tbody>
</table>
<p>Women in the control group would be:</p>
<pre class="r"><code># not treatment group & not men
these <- ! ( group == "treat" ) & ! ( gender == "male" )
dat[ these , ]</code></pre>
<pre><code>## group gender
## 4 control female</code></pre>
</div>
</div>
<div id="care-with-logical-statements" class="section level1" number="3">
<h1><span class="header-section-number">3</span> Care With Logical Statements</h1>
<p>A common mistake you will make when you first start constructing logical statements is to define a group, and then since you are in a hurry you flip the logic and think you are making a valid comparison.</p>
<blockquote>
<p>Do bearded men earn more than men without beards?</p>
</blockquote>
<p>The <strong>opposite-of</strong> “men with beards” (“male” & “beards”) is not men without beards, it is men without beards OR women (with or without beards).</p>
<div class="figure"><span style="display:block;" id="fig:unnamed-chunk-35"></span>
<img src="figures/bearded_men.png" alt="Compound statements can be tricky" width="60%" />
<p class="caption">
Figure 3.1: Compound statements can be tricky
</p>
</div>
<p>In the example above, the statement “NOT bearded men” means all people outside of the category of men without beards (the “complement”), which includes women with or without beards as well.</p>
<p>Also note that parentheses matter. Compare this statement to the statement above:</p>
<pre><code>! gender == "male" & beard == TRUE</code></pre>
<p>Because we excluded the parentheses this statement now defines the group “NOT men AND with beards”, or bearded women.</p>
<div class="figure"><span style="display:block;" id="fig:unnamed-chunk-36"></span>
<img src="figures/compound_logical_statements.png" alt="Examples of group construction with compound statements" width="90%" />
<p class="caption">
Figure 3.2: Examples of group construction with compound statements
</p>
</div>
<p>It’s important to note that the <strong>opposite-of</strong> operator does not flip the LOGIC of the question, it only flips TRUES and FALSE in the produced vector.</p>
<pre class="r"><code>group == "treat" & gender == "male" </code></pre>
<pre><code>## [1] TRUE FALSE FALSE FALSE</code></pre>
<pre class="r"><code>! ( group == "treat" & gender == "male" )</code></pre>
<pre><code>## [1] FALSE TRUE TRUE TRUE</code></pre>
<p>Pay close attention to the order of operations when constructing logical statements.</p>
<p>Since all logical operators have the same precedence, the <strong>opposite-of</strong> operator will be applied first here, then the <strong>and</strong> operator. Thus these are not the same:</p>
<table style="width:28%;">
<colgroup>
<col width="13%" />
<col width="13%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">group</th>
<th align="center">gender</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">treat</td>
<td align="center">male</td>
</tr>
<tr class="even">
<td align="center">treat</td>
<td align="center">female</td>
</tr>
<tr class="odd">
<td align="center">control</td>
<td align="center">male</td>
</tr>
<tr class="even">
<td align="center">control</td>
<td align="center">female</td>
</tr>
</tbody>
</table>
<pre class="r"><code>these <- ! ( group == "treat" & gender == "male" )
dat[ these , ] </code></pre>
<table style="width:40%;">
<colgroup>
<col width="12%" />
<col width="13%" />
<col width="13%" />
</colgroup>
<thead>
<tr class="header">
<th align="center"> </th>
<th align="center">group</th>
<th align="center">gender</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center"><strong>2</strong></td>
<td align="center">treat</td>
<td align="center">female</td>
</tr>
<tr class="even">
<td align="center"><strong>3</strong></td>
<td align="center">control</td>
<td align="center">male</td>
</tr>
<tr class="odd">
<td align="center"><strong>4</strong></td>
<td align="center">control</td>
<td align="center">female</td>
</tr>
</tbody>
</table>
<pre class="r"><code>these <- ! group == "treat" & gender == "male"
dat[ these , ]</code></pre>
<table style="width:40%;">
<colgroup>
<col width="12%" />
<col width="13%" />
<col width="13%" />
</colgroup>
<thead>
<tr class="header">
<th align="center"> </th>
<th align="center">group</th>
<th align="center">gender</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center"><strong>3</strong></td>
<td align="center">control</td>
<td align="center">male</td>
</tr>
</tbody>
</table>
</div>
<div id="advanced-operations-with-logical-vectors" class="section level1" number="4">
<h1><span class="header-section-number">4</span> Advanced Operations with Logical Vectors</h1>
<div id="find-and-replace" class="section level2" number="4.1">
<h2><span class="header-section-number">4.1</span> Find and Replace</h2>
<p>We can use selector variables to replace observations with new values using the assignment operator. This is similar to a find and replace operation.</p>
<pre class="r"><code>animals <- c( "mole", "mouse", "shrew", "mouse", "rat", "shrew" )
# the lab assistant incorrectly identified the shrews
animals</code></pre>
<pre><code>## [1] "mole" "mouse" "shrew" "mouse" "rat" "shrew"</code></pre>
<pre class="r"><code>animals[ animals == "shrew" ] <- "possum"
animals</code></pre>
<pre><code>## [1] "mole" "mouse" "possum" "mouse" "rat" "possum"</code></pre>
<p>We don’t know if linda received the treatment:</p>
<table style="width:31%;">
<colgroup>
<col width="11%" />
<col width="19%" />
</colgroup>
<thead>
<tr class="header">
<th align="center">name</th>
<th align="center">study.group</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="center">adam</td>
<td align="center">treatment</td>
</tr>
<tr class="even">
<td align="center">jamal</td>
<td align="center">control</td>
</tr>
<tr class="odd">
<td align="center">linda</td>
<td align="center">treatment</td>
</tr>
<tr class="even">
<td align="center">sriti</td>
<td align="center">control</td>
</tr>
</tbody>
</table>
<pre class="r"><code># replace
study.group[ name == "linda" ] <- NA
study.group</code></pre>
<pre><code>## [1] "treatment" "control" NA "control"</code></pre>
</div>
<div id="nas-in-logical-statements" class="section level2" number="4.2">
<h2><span class="header-section-number">4.2</span> NAs in Logical Statements</h2>
<p>Recall that missing values are an extremely important concept in statistics. If one-third of our survey sample reports that they never smoked pot, one-third reports they have smoked pot, and one-third did not answer the question, then what do we report for the proportion of the population that has smoked pot?</p>
<p>We might prefer to be cautious and count only the people that have confirmed they have smoked pot, resulting in an estimate of 33.3%.</p>
<p>If we throw out the missing data, then 50% of respondents have smoked pot.</p>
<p>If we assume those that refuse to answer have likely smoked pot, our estimate might be 66.6% of the sample.</p>
<p>These different results are a function of how we treat the missing data in our survey, so it is important that we can keep track of missing values, especially during subset operations.</p>
<p>Note how NAs effect compound logical statements:</p>
<pre class="r"><code>TRUE & TRUE</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>TRUE & FALSE</code></pre>
<pre><code>## [1] FALSE</code></pre>