-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathbk00_vectors-and-lists.html
709 lines (625 loc) · 23.9 KB
/
bk00_vectors-and-lists.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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Vectors and lists</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/flatly.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>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<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>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</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>
<style type="text/css">
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;
}
.table th:not([align]) {
text-align: left;
}
</style>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
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;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 60px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 65px;
margin-top: -65px;
}
.section h2 {
padding-top: 65px;
margin-top: -65px;
}
.section h3 {
padding-top: 65px;
margin-top: -65px;
}
.section h4 {
padding-top: 65px;
margin-top: -65px;
}
.section h5 {
padding-top: 65px;
margin-top: -65px;
}
.section h6 {
padding-top: 65px;
margin-top: -65px;
}
.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: #ffffff;
}
.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>
// 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.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
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;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default 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">purrr tutorial</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Lessons and examples</a>
</li>
<li>
<a href="more-resources.html">More resources</a>
</li>
<li>
<a href="talks.html">Talks</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="about.html">About</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Vectors and lists</h1>
</div>
<div id="atomic-vectors" class="section level3">
<h3>Atomic vectors</h3>
<p>It is useful to understand lists as a data structure that generalizes atomic vectors. So we really need to start there.</p>
<p>The garden variety R object is an <strong>atomic vector</strong> like these:</p>
<pre class="r"><code>(v_log <- c(TRUE, FALSE, FALSE, TRUE))
#> [1] TRUE FALSE FALSE TRUE
(v_int <- 1:4)
#> [1] 1 2 3 4
(v_doub <- 1:4 * 1.2)
#> [1] 1.2 2.4 3.6 4.8
(v_char <- letters[1:4])
#> [1] "a" "b" "c" "d"</code></pre>
<p>Atomic vectors are homogeneous. Each <strong>atom</strong> has the same flavor, by which I roughly mean type or storage mode, and is a scalar, by which I mean “has length one”. The above examples cover the most common flavors of R vectors (logical, integer, double, character), though you will eventually encounter more exotic ones.</p>
<div id="exercises" class="section level4">
<h4>Exercises</h4>
<ol style="list-style-type: decimal">
<li>Define the vectors above or similar. Use the family of <code>is.*()</code> functions to confirm vector type, e.g. <code>is.logical()</code>. You will need to guess or look some of them up. <em>Long-term, you may wish to explore the <code>rlang::is_*()</code> family of functions.</em></li>
<li>What do <code>is.numeric()</code>, <code>is.integer()</code>, and <code>is.double()</code> return for the vectors that hold floating point number versus integers?</li>
</ol>
<p>You can construct a vector “by hand” with the <code>c()</code> function. We used it above to construct the logical vector. All the other vectors came about through other means and this is indicative of real life: most vectors aren’t made explicitly with <code>c()</code>. They tend to be created with some generator, like the <code>1:n</code> shortcut, or via transformation of an existing object.</p>
<p>To “index a vector” means to address specific elements or atoms, either for reading or writing. We index a vector using square brackets, like so: <code>x[something]</code>. There are several ways to express which elements you want, i.e. there are several valid forms for <code>something</code>:</p>
<ul>
<li><p>logical vector: keep elements of <code>x</code> for which <code>something</code> is <code>TRUE</code> and drop those for which it’s <code>FALSE</code></p>
<pre class="r"><code>v_char[c(FALSE, FALSE, TRUE, TRUE)]
#> [1] "c" "d"
v_char[v_log]
#> [1] "a" "d"</code></pre></li>
<li>integer vector, all positive: the elements specified in <code>something</code> are kept</li>
<li><p>negative integers, all negative: the elements specified in <code>something</code> are dropped</p>
<pre class="r"><code>v_doub[2:3]
#> [1] 2.4 3.6
v_char[-4]
#> [1] "a" "b" "c"</code></pre></li>
<li><p>character vector: presumes that <code>x</code> is a named vector and the elements whose names are specified in <code>something</code> are kept <em>not shown here, since none of our vectors are named</em></p></li>
</ul>
</div>
<div id="exercises-1" class="section level4">
<h4>Exercises</h4>
<ol style="list-style-type: decimal">
<li>What happens when you request the zero-th element of one of our vectors?</li>
<li>What happens when you ask for an element that is past the end of the vector, i.e. request <code>x[k]</code> when the length of <code>x</code> is less than <code>k</code>?</li>
<li>We indexed a vector <code>x</code> with a vector of positive integers that is shorter than <code>x</code>. What happens if the indexing vector is <strong>longer</strong> than <code>x</code>?</li>
<li>We indexed <code>x</code> with a logical vector of the same length. What happen if the indexing vector is <strong>shorter</strong> than <code>x</code>?</li>
</ol>
<p>Do the exercises and you’ll see it’s possible to get an atomic vector of length zero and also to get elements that are <code>NA</code>. Notice that, in both of these scenarios, the underlying variable type is retained.</p>
<pre class="r"><code>v_int[0]
#> integer(0)
typeof(v_int[0])
#> [1] "integer"
v_doub[100]
#> [1] NA
typeof(v_doub[100])
#> [1] "double"</code></pre>
<p>Yes, there are different flavors of <code>NA</code>!</p>
</div>
</div>
<div id="coercion" class="section level3">
<h3>Coercion</h3>
<p>Even though R’s vectors have a specific type, it’s quite easy to convert them to another type. This is called <strong>coercion</strong>. As a language for data analysis, this flexibility works mostly to our advantage. It’s why we generally don’t stress out over integer versus double in R. It’s why we can compute a proportion as the mean of a logical vector (we exploit automatic coercion to integer in this case). But unexpected coercion is a rich source of programming puzzles, so always consider this possibility when debugging.</p>
<p>There’s a hierarchy of types: the more primitive ones cheerfully and silently convert to those higher up in the food chain. Here’s the order:</p>
<ol style="list-style-type: decimal">
<li>logical</li>
<li>integer</li>
<li>double</li>
<li>character</li>
</ol>
<p>For explicit coercion, use the <code>as.*()</code> functions.</p>
<pre class="r"><code>v_log
#> [1] TRUE FALSE FALSE TRUE
as.integer(v_log)
#> [1] 1 0 0 1
v_int
#> [1] 1 2 3 4
as.numeric(v_int)
#> [1] 1 2 3 4
v_doub
#> [1] 1.2 2.4 3.6 4.8
as.character(v_doub)
#> [1] "1.2" "2.4" "3.6" "4.8"
as.character(as.numeric(as.integer(v_log)))
#> [1] "1" "0" "0" "1"</code></pre>
<p>But coercion can also be triggered by other actions, such as assigning a scalar of the wrong type into an existing vector. Watch how easily I turn a numeric vector into character.</p>
<pre class="r"><code>v_doub_copy <- v_doub
str(v_doub_copy)
#> num [1:4] 1.2 2.4 3.6 4.8
v_doub_copy[3] <- "uhoh"
str(v_doub_copy)
#> chr [1:4] "1.2" "2.4" "uhoh" "4.8"</code></pre>
<p>Our numeric vector was silently coerced to character. Notice that R did this quietly, with no fanfare. Again, when debugging, always give serious thought to this question: Is this object of the type I think it is? How sure am I about that?</p>
<p>I end the discussion of atomic vectors with two specific examples of “being intentional about type”.</p>
<ul>
<li>Use of type-specific <code>NA</code>s when doing setup.</li>
<li>Use of <code>L</code> to explicitly request integer. This looks weird but is a nod to short versus long integers. Just accept that this is how we force a literal number to be interpreted as an integer in R.</li>
</ul>
<pre class="r"><code>(big_plans <- rep(NA_integer_, 4))
#> [1] NA NA NA NA
str(big_plans)
#> int [1:4] NA NA NA NA
big_plans[3] <- 5L
## note that big_plans is still integer!
str(big_plans)
#> int [1:4] NA NA 5 NA
## note that omitting L results in coercion of big_plans to double
big_plans[1] <- 10
str(big_plans)
#> num [1:4] 10 NA 5 NA</code></pre>
<p>As the tutorial goes on, you’ll see how the purrr package makes it easier for you to be intentional and careful about type in your R programming.</p>
<div id="exercises-2" class="section level4">
<h4>Exercises</h4>
<ol style="list-style-type: decimal">
<li>Recall the hieararchy of the most common atomic vector types: logical < integer < numeric < character. Try to use the <code>as.*()</code> functions to go the wrong way. Call <code>as.logical()</code>, <code>as.integer()</code>, and <code>as.numeric()</code> on a character vector, such as <code>letters</code>. What happens?</li>
</ol>
</div>
</div>
<div id="lists" class="section level3">
<h3>Lists</h3>
<p>What if you need to hold something that violates the constraints imposed by an atomic vector? I.e. one or both of these is true:</p>
<ul>
<li>Individual atoms might have length greater than 1.</li>
<li>Individual atoms might not be of the same flavor.</li>
</ul>
<p>You need a list!</p>
<p><strong>A list is actually still a vector in R, but it’s not an atomic vector.</strong> We construct a list explicitly with <code>list()</code> but, like atomic vectors, most lists are created some other way in real life.</p>
<pre class="r"><code>(x <- list(1:3, c("four", "five")))
#> [[1]]
#> [1] 1 2 3
#>
#> [[2]]
#> [1] "four" "five"
(y <- list(logical = TRUE, integer = 4L, double = 4 * 1.2, character = "character"))
#> $logical
#> [1] TRUE
#>
#> $integer
#> [1] 4
#>
#> $double
#> [1] 4.8
#>
#> $character
#> [1] "character"
(z <- list(letters[26:22], transcendental = c(pi, exp(1)), f = function(x) x^2))
#> [[1]]
#> [1] "z" "y" "x" "w" "v"
#>
#> $transcendental
#> [1] 3.141593 2.718282
#>
#> $f
#> function(x) x^2</code></pre>
<p>We have explicit proof above that list components can</p>
<ul>
<li>Be heterogeneous, i.e. can be of different “flavors”. Heck, they don’t even need to be atomic vectors – you can stick a function in there!</li>
<li>Have different lengths.</li>
<li>Have names. Or not. Or some of both.</li>
</ul>
<div id="exercises-3" class="section level4">
<h4>Exercises</h4>
<ol style="list-style-type: decimal">
<li>Make the lists <code>x</code>, <code>y</code>, and <code>z</code> as shown above. Use <code>is.*()</code> functions to get to know these objects. Try to get some positive and negative results, i.e. establish a few things that <code>x</code> is and is NOT. Make sure to try <code>is.list()</code>, <code>is.vector()</code>, <code>is.atomic()</code>, and <code>is.recursive()</code>. <em>Long-term, you may wish to explore the <code>rlang::is_*()</code> family of functions.</em></li>
</ol>
<p>It should be clear that lists are much more general than atomic vectors. But they also share many properties: for example, they have length and they can be indexed.</p>
</div>
</div>
<div id="list-indexing" class="section level3">
<h3>List indexing</h3>
<p>There is a new wrinkle when you index a list vs an atomic vector. There are 3 ways to index a list and the differences are very important:</p>
<ol style="list-style-type: decimal">
<li><p>With single square brackets, i.e. just like we indexed atomic vectors. Note this <strong>always returns a list</strong>, even if we request a single component.</p>
<pre class="r"><code>x[c(FALSE, TRUE)]
#> [[1]]
#> [1] "four" "five"
y[2:3]
#> $integer
#> [1] 4
#>
#> $double
#> [1] 4.8
z["transcendental"]
#> $transcendental
#> [1] 3.141593 2.718282</code></pre></li>
<li><p>With double square brackets, which is new to us. This can only be used to access a single component and it returns the “naked” component. You can request a component with a positive integer or by name.</p>
<pre class="r"><code>x[[2]]
#> [1] "four" "five"
y[["double"]]
#> [1] 4.8</code></pre></li>
<li><p>With the <code>$</code>, which you may already use to extract a single variable from a data frame (which is a special kind of list!). Like <code>[[</code>, this can only be used to access a single component, but it is even more limited: You must specify the component by name.</p>
<pre class="r"><code>z$transcendental
#> [1] 3.141593 2.718282</code></pre></li>
</ol>
<p>My favorite explanation of the difference between the list-preserving indexing provided by <code>[</code> and the always-simplifying behaviour of <code>[[</code> is given by the <a href="http://r4ds.had.co.nz/vectors.html#lists-of-condiments">“pepper shaker photos” in R for Data Science</a>. Highly recommended!</p>
<div id="exercises-4" class="section level4">
<h4>Exercises</h4>
<ol style="list-style-type: decimal">
<li>Use <code>[</code>, <code>[[</code>, and <code>$</code> to access the second component of the list <code>z</code>, which bears the name “transcendental”. Use the <code>length()</code> and the <code>is.*()</code> functions explored elsewhere to study the result. Which methods of indexing yield the same result vs. different?</li>
<li><p>Put the same data into an atomic vector and a list:</p>
<pre class="r"><code>my_vec <- c(a = 1, b = 2, c = 3)
my_list <- list(a = 1, b = 2, c = 3)</code></pre>
<p>Use <code>[</code> and <code>[[</code> to attempt to retrieve elements 2 and 3 from <code>my_vec</code> and <code>my_list</code>. What succeeds vs. fails? What if you try to retrieve element 2 alone? Does <code>[[</code> even work on atomic vectors? Compare and contrast the results from the various combinations of indexing method and input object.</p></li>
</ol>
</div>
</div>
<div id="vectorized-operations" class="section level3">
<h3>Vectorized operations</h3>
<p>Many people are shocked to learn that the garden variety R object is a vector. A related fact is that many operations “just work” element-wise on vectors, with no special effort. This often requires an adjustment for people coming from other languages. Your code can be simpler than you think!</p>
<p>Consider how to square the integers 1 through <code>n</code>. The brute force method might look like:</p>
<pre class="r"><code>n <- 5
res <- rep(NA_integer_, n)
for (i in seq_len(n)) {
res[i] <- i ^ 2
}
res
#> [1] 1 4 9 16 25</code></pre>
<p>The R way is:</p>
<pre class="r"><code>n <- 5
seq_len(n) ^ 2
#> [1] 1 4 9 16 25</code></pre>
<p>Element-wise or vectorized operations are “baked in” to a surprising degree in R. Which is great. You get used to it soon enough.</p>
<p>But then there’s the let down. This happens for atomic vectors, but not, in general, for lists. This makes sense because, in general, there is no reason to believe that the same sorts of operations make sense for each component of a list. Unlike atomic vectors, they are heterogeneous.</p>
<p>Here’s a demo using <code>as.list()</code> to create the list version of an atomic vector.</p>
<pre class="r"><code>## elementwise exponentiation of numeric vector works
exp(v_doub)
#> [1] 3.320117 11.023176 36.598234 121.510418
## put the same numbers in a list and ... this no longer works :(
(l_doub <- as.list(v_doub))
#> [[1]]
#> [1] 1.2
#>
#> [[2]]
#> [1] 2.4
#>
#> [[3]]
#> [1] 3.6
#>
#> [[4]]
#> [1] 4.8
exp(l_doub)
#> Error in exp(l_doub): non-numeric argument to mathematical function</code></pre>
<p>So, how do you apply a function elementwise to a list?! What is the list analogue of <code>exp(v_doub)</code>?</p>
<p>Use <code>purrr::map()</code>! The first argument is the list to operate on. The second is the function to apply.</p>
<pre class="r"><code>library(purrr)
map(l_doub, exp)
#> [[1]]
#> [1] 3.320117
#>
#> [[2]]
#> [1] 11.02318
#>
#> [[3]]
#> [1] 36.59823
#>
#> [[4]]
#> [1] 121.5104</code></pre>
<p>Vocabulary: we talk about this as “mapping the function <code>exp()</code> over the list <code>l_doub</code>”. Conceptually, we loop over the elements of the list and apply a function.</p>
<pre class="r"><code>my_list <- list(...)
my_output <- ## something of an appropriate size and flavor
for(i in seq_along(my_list)) {
my_output[[i]] <- f(my_list([[i]]))
}</code></pre>
<p>A major objective of this tutorial is to show you how to avoid writing these explicit <code>for()</code> loops yourself.</p>
</div>
<i class="fab fa-creative-commons fa-2x"></i><i class="fab fa-creative-commons-by fa-2x"></i><i class="fab fa-creative-commons-sa fa-2x"></i>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open')
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>