-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathFunctional-Programming-in-R.html
More file actions
1880 lines (1758 loc) · 77.8 KB
/
Functional-Programming-in-R.html
File metadata and controls
1880 lines (1758 loc) · 77.8 KB
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 lang="en">
<head>
<title>Functional Programming in R: First-Class Functions & purrr Explained</title>
<meta charset="utf-8">
<meta name="Description" content="Master functional programming in R with first-class functions, purrr map/reduce, closures, and function factories. Interactive examples you can run in your browser.">
<meta name="Keywords" content="functional programming in R, first-class functions R, purrr map, purrr reduce, R closures, function factories R, anonymous functions R, lapply vs map">
<meta name="Distribution" content="Global">
<meta name="Author" content="Selva Prabhakaran">
<meta name="Robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/screenshots/iconb-64.png" type="image/x-icon" />
<link rel="canonical" href="https://r-statistics.co/Functional-Programming-in-R.html">
<link rel="alternate" type="application/atom+xml" title="r-statistics.co" href="https://r-statistics.co/feed.xml">
<link href="www/bootstrap.min.css" rel="stylesheet">
<link href="www/highlight.css" rel="stylesheet">
<link href="css/main.css?v=9" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&family=IBM+Plex+Serif:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap"
rel="stylesheet">
<!-- Color Script -->
<style type="text/css">
a {
color: #3F73D8;
}
li {
line-height: 1.65;
}
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
/* Wider container for better content space */
@media (min-width: 1200px) {
.container { max-width: 1280px; }
}
/* Custom column widths: narrower sidebars, wider content */
@media (min-width: 768px) {
#nav { width: 20%; }
#content { width: 60%; padding-left: 20px; padding-right: 20px; }
#toc-sidebar { width: 20%; }
}
@media (min-width: 1200px) {
#nav { width: 18%; }
#content { width: 62%; }
#toc-sidebar { width: 20%; }
}
/* Prevent ad overflow */
#nav, #content, #toc-sidebar {
overflow: hidden;
}
</style>
<!-- Open Graph -->
<meta property="og:title" content="Functional Programming in R: First-Class Functions & purrr Explained">
<meta property="og:description" content="Master functional programming in R with first-class functions, purrr map/reduce, closures, and function factories. Interactive examples you can run in your browser.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://r-statistics.co/Functional-Programming-in-R.html">
<meta property="og:site_name" content="r-statistics.co">
<meta property="og:image" content="https://r-statistics.co/screenshots/iconb-64.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Functional Programming in R: First-Class Functions & purrr Explained">
<meta name="twitter:description" content="Master functional programming in R with first-class functions, purrr map/reduce, closures, and function factories. Interactive examples you can run in your browser.">
<!-- JSON-LD Structured Data -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": ["TechArticle", "LearningResource"],
"headline": "Functional Programming in R: First-Class Functions & purrr Explained",
"description": "Master functional programming in R with first-class functions, purrr map/reduce, closures, and function factories. Interactive examples you can run in your browser.",
"author": {"@type": "Person", "name": "Selva Prabhakaran"},
"publisher": {"@type": "Organization", "name": "r-statistics.co"},
"url": "https://r-statistics.co/Functional-Programming-in-R.html",
"datePublished": "2026-04-03",
"dateModified": "2026-04-03",
"inLanguage": "en",
"educationalLevel": "Intermediate",
"programmingLanguage": "R"
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{"@type": "Question", "name": "Is R a functional programming language?", "acceptedAnswer": {"@type": "Answer", "text": "R is a multi-paradigm language with strong functional programming support. Functions are first-class citizens, and the language was heavily influenced by Scheme (a functional Lisp dialect). You can write R in a functional, imperative, or object-oriented style."}},
{"@type": "Question", "name": "Should I use lapply() or purrr::map()?", "acceptedAnswer": {"@type": "Answer", "text": "Both work well. Use lapply() when you want zero dependencies or you're writing a package. Use purrr::map() when you want type-safe variants (map_dbl, map_chr), better error handling (safely, possibly), and a consistent API. For interactive analysis, purrr is usually more convenient."}},
{"@type": "Question", "name": "What's the difference between a closure and a regular function?", "acceptedAnswer": {"@type": "Answer", "text": "All user-defined functions in R are technically closures — they carry a reference to the environment where they were created. The term \"closure\" is most useful when a function captures variables from an enclosing function, like when a function factory returns an inner function that remembers the factory's arguments."}},
{"@type": "Question", "name": "Why use map() instead of a for loop?", "acceptedAnswer": {"@type": "Answer", "text": "Readability and safety. A map() call says \"apply this function to every element\" in one line. A for loop requires initializing a container, writing the loop header, and indexing correctly. With map(), there's no index variable to mess up and no container to pre-allocate."}},
{"@type": "Question", "name": "Can functional programming be slower than loops in R?", "acceptedAnswer": {"@type": "Answer", "text": "In most practical cases, the performance difference is negligible. Both lapply() and map() use optimized C code internally. The real performance gains come from vectorized operations (which avoid both loops and functionals) or parallelization. Use functional style for clarity, and optimize only when profiling reveals a bottleneck."}}
]
}
</script>
<!-- WebR Interactive R Code -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<style>
/* --- Loading banner: compact, collapses when ready --- */
.webr-loading-banner {
padding: 8px 16px;
background: #f0f4ff;
color: #3b5998;
text-align: center;
margin: 0 0 8px 0;
border-radius: 6px;
font-size: 13px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
border: 1px solid #c7d2fe;
transition: all 0.4s ease;
overflow: hidden;
max-height: 50px;
}
.webr-loading-banner.ready {
background: #ecfdf5;
color: #166534;
border-color: #86efac;
}
.webr-loading-banner.hidden {
max-height: 0;
padding: 0 16px;
margin: 0;
border-color: transparent;
opacity: 0;
}
/* --- Run All bar (subtle with background) --- */
.webr-runall-bar {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 10px;
padding: 7px 14px;
margin: 0 0 18px 0;
background: #f8fafb;
border: 1px solid #edf0f3;
border-radius: 8px;
opacity: 0;
transform: translateY(-4px);
transition: opacity 0.3s ease, transform 0.3s ease;
}
.webr-runall-bar.visible { opacity: 1; transform: translateY(0); }
.webr-runall-label {
font-size: 11px;
color: #9ca3af;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
display: flex;
align-items: center;
gap: 5px;
}
.webr-runall-label::before {
content: '';
width: 6px; height: 6px;
border-radius: 50%;
background: #2da44e;
flex-shrink: 0;
}
.webr-runall-btn {
background: none;
color: #3f73d8;
border: 1px solid #d0d7de;
padding: 4px 12px;
border-radius: 6px;
font-size: 11px;
font-weight: 400;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
transition: all 0.15s ease;
}
.webr-runall-btn:hover { background: #f6f8fa; border-color: #3f73d8; }
.webr-runall-btn:disabled { color: #a5b4d4; cursor: wait; }
.webr-runall-btn.running { color: #d29922; border-color: #d29922; animation: pulse-run 1.5s ease-in-out infinite; }
/* --- Code block container --- */
.webr-container {
margin: 22px 0;
border: 1px solid #e1e4e8;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.06), 0 0 1px rgba(0,0,0,0.1);
transition: box-shadow 0.2s ease;
}
.webr-container:hover {
box-shadow: 0 4px 16px rgba(0,0,0,0.1), 0 0 1px rgba(0,0,0,0.12);
}
.webr-container:focus-within {
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59,130,246,0.15), 0 2px 8px rgba(0,0,0,0.06);
}
/* --- Button bar (below code editor) --- */
.webr-buttons {
padding: 6px 10px;
background: #f7f8fa;
border-top: 1px solid #e1e4e8;
display: flex;
justify-content: space-between;
align-items: center;
}
.webr-buttons-left { display: flex; gap: 6px; align-items: center; }
.webr-buttons-right { display: flex; gap: 6px; align-items: center; }
/* --- Keyboard hint --- */
.webr-kbd-hint {
font-size: 10px;
color: #9ca3af;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
.webr-kbd-hint kbd {
background: #f0f1f3;
border: 1px solid #d1d5db;
border-radius: 3px;
padding: 1px 4px;
font-size: 10px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
box-shadow: 0 1px 0 rgba(0,0,0,0.06);
}
/* --- Copy button --- */
.webr-copy-btn {
background: none;
border: 1px solid #d0d7de;
color: #656d76;
padding: 3px 8px;
border-radius: 6px;
font-size: 12px;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
transition: all 0.15s ease;
display: flex;
align-items: center;
gap: 4px;
}
.webr-copy-btn:hover { background: #f6f8fa; color: #24292f; border-color: #c0c8d0; }
.webr-copy-btn.copied { color: #2da44e; border-color: #2da44e; }
/* --- CodeMirror editor --- */
.webr-editor .CodeMirror {
height: auto;
min-height: 48px;
font-size: 14px;
font-family: 'JetBrains Mono', 'Fira Code', 'Inconsolata', 'Consolas', monospace;
line-height: 1.6;
background: #fafbfd;
padding: 4px 0;
}
.webr-editor .CodeMirror-gutters {
background: #f0f2f5;
border-right: 1px solid #e1e4e8;
padding-right: 2px;
}
.webr-editor .CodeMirror-linenumber {
color: #a0a8b4;
font-size: 11px;
padding: 0 6px 0 8px;
min-width: 28px;
}
.webr-editor .CodeMirror-cursor { border-left-color: #3b82f6; border-left-width: 2px; }
.webr-editor .CodeMirror-selected { background: #c8e1ff !important; }
.webr-editor .CodeMirror-activeline-background { background: #f0f4ff; }
.webr-editor .CodeMirror-matchingbracket { color: #0969da !important; font-weight: 700; background: #ddf4ff; border-radius: 2px; }
/* --- R syntax colors (refined) --- */
.webr-editor .cm-keyword { color: #cf222e; font-weight: 500; }
.webr-editor .cm-atom { color: #8250df; }
.webr-editor .cm-number { color: #0550ae; }
.webr-editor .cm-def { color: #8250df; }
.webr-editor .cm-variable { color: #24292f; }
.webr-editor .cm-variable-2 { color: #953800; }
.webr-editor .cm-variable-3 { color: #0550ae; }
.webr-editor .cm-property { color: #0550ae; }
.webr-editor .cm-operator { color: #cf222e; }
.webr-editor .cm-comment { color: #6e7781; font-style: italic; }
.webr-editor .cm-string { color: #0a3069; }
.webr-editor .cm-string-2 { color: #0a3069; }
.webr-editor .cm-builtin { color: #8250df; font-weight: 500; }
/* --- Run button --- */
.webr-run-btn {
background: #3f73d8;
color: #fff;
border: none;
padding: 4px 14px;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
transition: all 0.15s ease;
}
.webr-run-btn:hover { background: #2c5fbe; }
.webr-run-btn:active { background: #254fa0; }
.webr-run-btn:disabled { background: #a5b4d4; cursor: wait; }
.webr-run-btn.running { background: #d29922; animation: pulse-run 1.5s ease-in-out infinite; }
@keyframes pulse-run { 0%, 100% { opacity: 1; } 50% { opacity: 0.8; } }
/* --- Reset button --- */
.webr-reset-btn {
background: none;
color: #656d76;
border: 1px solid #d0d7de;
padding: 3px 10px;
border-radius: 6px;
font-size: 12px;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
transition: all 0.15s ease;
}
.webr-reset-btn:hover { background: #f6f8fa; color: #24292f; border-color: #c0c8d0; }
/* --- Output panel --- */
.webr-output {
margin: 0;
padding: 14px 16px;
background: #1e2228;
color: #c9d1d9;
font-family: 'JetBrains Mono', 'Fira Code', 'Inconsolata', 'Consolas', monospace;
font-size: 13px;
line-height: 1.6;
max-height: 400px;
overflow-y: auto;
white-space: pre-wrap;
display: none;
border-top: 2px solid #2da44e;
}
.webr-output::-webkit-scrollbar { width: 8px; }
.webr-output::-webkit-scrollbar-track { background: #1e2228; }
.webr-output::-webkit-scrollbar-thumb { background: #444d56; border-radius: 4px; }
.webr-output.has-content { display: block; }
.webr-output.has-error { color: #f85149; border-top-color: #f85149; }
/* --- Plot output --- */
.webr-plot-output { text-align: center; padding: 16px; background: #fff; display: none; border-top: 1px solid #e1e4e8; }
.webr-plot-output.has-content { display: block; }
.webr-plot-output img, .webr-plot-output canvas { max-width: 100%; height: auto; border-radius: 6px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); }
.mermaid { margin: 15px 0; text-align: center; }
</style>
<!-- Add Google search -->
<script language="Javascript" type="text/javascript">
function my_search_google()
{
var query = document.getElementById("my-google-search").value;
window.open("https://google.com/search?q=" + query
+ "%20site:" + "https://r-statistics.co");
}
</script>
</head>
<body>
<div class="container">
<div class="masthead">
<!--
<ul class="nav nav-pills pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Table of contents<b class="caret"></b>
</a>
<ul class="dropdown-menu pull-right" role="menu">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</ul>
-->
<div class="site-header" style="display:flex; justify-content:space-between; align-items:center; padding: 12px 0 8px 0;">
<h3 style="margin:0;"><a href="/" style="text-decoration:none;">r-statistics.co</a><small style="color:#999; margin-left:6px;"> by Selva Prabhakaran</small></h3>
<div style="display:flex; align-items:center; gap:18px;">
<a href="/about/" style="font-size:14px; color:#666; text-decoration:none;">About</a>
<button id="dark-mode-toggle" aria-label="Toggle dark mode" title="Toggle dark mode"
style="background:none;border:1px solid #d0d7de;border-radius:6px;padding:4px 8px;cursor:pointer;font-size:16px;line-height:1;color:#666;transition:all 0.2s;">
☽
</button>
<form onsubmit="my_search_google(); return false;" style="margin:0;">
<input type="text" class="form-control" id="my-google-search" placeholder="Search.." style="width:160px; height:32px; font-size:13px; border-radius:6px;">
</form>
</div>
</div>
<hr style="margin:0 0 16px 0;">
</div>
<div class="row">
<div class="col-xs-12 col-sm-3" id="nav">
<div id="sidebar-nav">
<!-- Loaded dynamically from www/sidebar.json by toc.js -->
</div>
</div>
<div id="content" class="col-xs-12 col-sm-7">
<p>R is a functional programming language at its core. Every operation you run — from subsetting a vector to fitting a model — relies on functions. But most R users treat functions as commands to call, not as objects to manipulate. That's the difference between using R and thinking in R.</p>
<h2>Introduction</h2>
<p>In most programming languages, functions are special. You define them, you call them, and that's it. R is different. In R, functions are <strong>first-class citizens</strong> — they're regular objects, just like numbers and character strings. You can assign a function to a variable, toss it into a list, pass it as an argument, or return it from another function.</p>
<p>This isn't just a language trivia fact. It's the foundation of a programming style called <strong>functional programming</strong> (FP) that makes your R code shorter, safer, and easier to reason about. Instead of writing loops that mutate variables step by step, you describe <em>what</em> to compute by passing functions to other functions.</p>
<p>In this tutorial, you'll learn:</p>
<ul>
<li>What "first-class functions" actually means (with proof)</li>
<li>How closures and function factories work</li>
<li>How to replace loops with <code>lapply()</code>, <code>sapply()</code>, and <code>purrr::map()</code></li>
<li>The complete purrr toolkit — <code>map</code>, <code>map2</code>, <code>pmap</code>, <code>walk</code>, <code>reduce</code></li>
<li>Error handling, function composition, and memoization</li>
<li>When functional programming helps and when it gets in the way</li>
</ul>
<h2>Functions Are First-Class Citizens</h2>
<p>What does it mean for functions to be "first-class"? It means functions are values. You can do with a function everything you can do with a number or a string.</p>
<p>Let's prove it with five demonstrations:</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># 1. Assign a function to a variable
square <- function(x) x^2
square(5)
#> [1] 25
# 2. Store functions in a list
math_ops <- list(
double = function(x) x * 2,
halve = function(x) x / 2,
negate = function(x) -x
)
math_ops$double(10)
#> [1] 20
math_ops$negate(7)
#> [1] -7</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># 3. Pass a function as an argument
apply_to_five <- function(f) f(5)
apply_to_five(sqrt)
#> [1] 2.236068
apply_to_five(function(x) x^3)
#> [1] 125</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># 4. Return a function from a function
make_adder <- function(n) {
function(x) x + n
}
add_10 <- make_adder(10)
add_10(3)
#> [1] 13
add_10(100)
#> [1] 110
# 5. Functions are objects — they have class and type
class(sqrt)
#> [1] "function"
typeof(mean)
#> [1] "closure"</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>That last line reveals something important: most R functions are <strong>closures</strong>, which means they carry their own environment with them. We'll explore that next.</p>
<blockquote><p><strong>Key insight:</strong> In R, there is no fundamental difference between a function and any other object. Functions can be created anywhere, passed anywhere, and stored in any data structure.</p></blockquote>
<h2>Anonymous Functions</h2>
<p>When you pass a small function as an argument, you often don't need to give it a name. These unnamed functions are called <strong>anonymous functions</strong>, and R has evolved three ways to write them.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r">numbers <- 1:5
# Style 1: Traditional (verbose)
sapply(numbers, function(x) x^2)
#> [1] 1 4 9 16 25
# Style 2: Lambda shorthand (R 4.1+, recommended)
sapply(numbers, \(x) x^2)
#> [1] 1 4 9 16 25
# Style 3: purrr formula shorthand (inside purrr only)
library(purrr)
map_dbl(numbers, ~ .x^2)
#> [1] 1 4 9 16 25</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># When to use each style:
# \(x) — preferred everywhere in modern R (clean, universal)
# ~ .x — only works inside purrr functions, convenient for quick transforms
# function(x) — use when you need multiple lines or clarity for beginners
# Multi-line anonymous function
result <- sapply(1:3, \(x) {
squared <- x^2
cubed <- x^3
squared + cubed
})
result
#> [1] 2 12 36</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>Use <code>\(x)</code> as your default. It's the modern R standard, works everywhere, and reads cleanly.</p>
<h2>Closures: Functions That Remember</h2>
<p>A <strong>closure</strong> is a function that captures variables from the environment where it was created. When <code>make_adder(10)</code> returned a function, that function <em>remembered</em> that <code>n</code> was 10 — even after <code>make_adder</code> finished running.</p>
<p>This is closures at work, and they're one of the most powerful ideas in R.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r">make_counter <- function() {
count <- 0
list(
increment = function() {
count <<- count + 1
count
},
get = function() count,
reset = function() {
count <<- 0
invisible(NULL)
}
)
}
counter <- make_counter()
counter$increment()
#> [1] 1
counter$increment()
#> [1] 2
counter$increment()
#> [1] 3
counter$get()
#> [1] 3
counter$reset()
counter$get()
#> [1] 0</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>The <code>count</code> variable lives inside <code>make_counter()</code>'s environment. The inner functions (increment, get, reset) are closures that captured that environment. The <code><<-</code> operator modifies <code>count</code> in the enclosing scope rather than creating a local copy.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Closures in practice: creating a family of power functions
make_power <- function(exp) {
function(x) x^exp
}
square <- make_power(2)
cube <- make_power(3)
fourth <- make_power(4)
sapply(1:5, square)
#> [1] 1 4 9 16 25
sapply(1:5, cube)
#> [1] 1 8 27 64 125
sapply(1:5, fourth)
#> [1] 1 16 81 256 625
# Each function remembers its own `exp` value
environment(square)$exp
#> [1] 2
environment(cube)$exp
#> [1] 3</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<blockquote><p><strong>When to use closures:</strong> Create closures when you need a family of similar functions that differ by one or two parameters. They're cleaner than copying and pasting code with minor variations.</p></blockquote>
<h2>Function Factories</h2>
<p>A <strong>function factory</strong> is a function whose job is to create other functions. You already saw two examples: <code>make_adder()</code> and <code>make_power()</code>. Let's look at a more practical one.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Factory: create formatters for different decimal places
make_formatter <- function(digits) {
function(x) format(round(x, digits), nsmall = digits)
}
fmt_2 <- make_formatter(2)
fmt_4 <- make_formatter(4)
pi_value <- 3.14159265
fmt_2(pi_value)
#> [1] "3.14"
fmt_4(pi_value)
#> [1] "3.1416"</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Factory: create threshold checkers
make_threshold <- function(cutoff, direction = "above") {
if (direction == "above") {
function(x) x > cutoff
} else {
function(x) x < cutoff
}
}
is_hot <- make_threshold(30, "above")
is_freezing <- make_threshold(0, "below")
temps <- c(-5, 10, 25, 35, 40)
is_hot(temps)
#> [1] FALSE FALSE FALSE TRUE TRUE
is_freezing(temps)
#> [1] TRUE FALSE FALSE FALSE FALSE</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>Function factories are especially useful in ggplot2. The <code>scale_*</code> functions like <code>scale_x_continuous(labels = scales::comma)</code> work this way — <code>scales::comma</code> is a function factory that returns a formatting function.</p>
<h2>Replacing Loops with Functionals</h2>
<p>A <strong>functional</strong> is a function that takes another function as input. The apply family (<code>lapply</code>, <code>sapply</code>, <code>vapply</code>) and purrr's <code>map()</code> are functionals. They're R's answer to <code>for</code> loops.</p>
<p>Let's solve the same problem three ways and compare:</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Task: compute the mean of each column in mtcars (first 5 columns)
data <- mtcars[, 1:5]
# Way 1: for loop
means_loop <- numeric(ncol(data))
names(means_loop) <- names(data)
for (i in seq_along(data)) {
means_loop[i] <- mean(data[[i]])
}
means_loop</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Way 2: sapply (base R functional)
means_sapply <- sapply(data, mean)
means_sapply</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Way 3: purrr::map_dbl (tidyverse functional)
library(purrr)
means_purrr <- map_dbl(data, mean)
means_purrr</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>All three produce identical results. But the functional versions are:</p>
<ul>
<li><strong>Shorter</strong> — one line instead of four</li>
<li><strong>Declarative</strong> — they say <em>what</em> to compute, not <em>how</em> to compute it</li>
<li><strong>Safer</strong> — no index variable to accidentally mess up</li>
</ul>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># Performance comparison
library(purrr)
big_list <- replicate(1000, rnorm(100), simplify = FALSE)
system.time(lapply(big_list, mean))
system.time(map(big_list, mean))
system.time({
result <- vector("list", length(big_list))
for (i in seq_along(big_list)) result[[i]] <- mean(big_list[[i]])
})</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>The three approaches have nearly identical speed. Use whichever reads clearest for your situation. Use <code>lapply()</code> when you want zero dependencies, <code>map()</code> when you want type-safe variants and a consistent API.</p>
<h2>The purrr Toolkit</h2>
<p>The purrr package provides a complete, consistent set of functionals. Here's the toolkit organized by what you need to do.</p>
<h4>map() — Apply a Function to Each Element</h4>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r">library(purrr)
# map() always returns a list
map(1:4, \(x) x^2)
# Type-specific variants return vectors
map_dbl(1:4, \(x) x^2) # double vector
#> [1] 1 4 9 16
map_chr(1:4, \(x) paste("Item", x)) # character vector
#> [1] "Item 1" "Item 2" "Item 3" "Item 4"
map_lgl(1:4, \(x) x > 2) # logical vector
#> [1] FALSE FALSE TRUE TRUE
map_int(1:4, \(x) as.integer(x * 10)) # integer vector
#> [1] 10 20 30 40</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<h4>map2() and pmap() — Multiple Inputs</h4>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># map2: iterate over two vectors in parallel
names <- c("Alice", "Bob", "Charlie")
ages <- c(30, 25, 35)
map2_chr(names, ages, \(n, a) paste(n, "is", a, "years old"))
#> [1] "Alice is 30 years old" "Bob is 25 years old" "Charlie is 35 years old"</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># pmap: iterate over any number of inputs (pass as list)
params <- list(
n = c(10, 20, 30),
mean = c(0, 5, 10),
sd = c(1, 2, 3)
)
samples <- pmap(params, \(n, mean, sd) rnorm(n, mean, sd))
map_dbl(samples, mean) # roughly 0, 5, 10</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<h4>walk() — Side Effects (No Return Value)</h4>
<p>Use <code>walk()</code> when you want to do something for each element but don't need a result back — like printing, writing files, or making plots.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># walk: call a function for side effects
filenames <- c("report_Q1.csv", "report_Q2.csv", "report_Q3.csv")
walk(filenames, \(f) cat("Processing:", f, "\n"))
#> Processing: report_Q1.csv
#> Processing: report_Q2.csv
#> Processing: report_Q3.csv</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<h4>imap() — Indexed Mapping</h4>
<p><code>imap()</code> passes both the element and its name (or index) to your function.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># imap: access both value and name/index
scores <- c(math = 92, science = 87, english = 95)
imap_chr(scores, \(score, subject) paste(subject, ":", score, "points"))
#> [1] "math : 92 points" "science : 87 points" "english : 95 points"</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<h4>reduce() — Combine Elements</h4>
<p><code>reduce()</code> takes a list and collapses it into a single value by repeatedly applying a two-argument function.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># reduce: collapse a list to a single value
reduce(1:5, `+`)
#> [1] 15
# Same as: ((((1 + 2) + 3) + 4) + 5) = 15
# Practical: find the intersection of multiple vectors
lists <- list(
c(1, 2, 3, 4, 5),
c(2, 3, 4, 6),
c(3, 4, 7, 8)
)
reduce(lists, intersect)
#> [1] 3 4
# accumulate: like reduce but keeps intermediate results
accumulate(1:5, `+`)
#> [1] 1 3 6 10 15</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<h2>Error Handling in Functional Code</h2>
<p>When you <code>map()</code> over many elements, one error stops everything. purrr provides wrappers that let you keep going.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r">library(purrr)
# A function that sometimes fails
safe_log <- function(x) {
if (x <= 0) stop("x must be positive")
log(x)
}
inputs <- list(10, -5, 100, 0, 42)
# safely() wraps each call — returns result + error
results <- map(inputs, safely(safe_log))
results[[1]] # success: result has value, error is NULL
results[[2]] # failure: result is NULL, error has message</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># possibly() is simpler — just returns a default on error
library(purrr)
safe_log <- function(x) {
if (x <= 0) stop("x must be positive")
log(x)
}
inputs <- list(10, -5, 100, 0, 42)
map_dbl(inputs, possibly(safe_log, otherwise = NA_real_))
#> [1] 2.302585 NA 4.605170 NA 3.737670</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<p>Use <code>possibly()</code> when you just want a default value. Use <code>safely()</code> when you need to inspect what went wrong.</p>
<h2>Function Operators</h2>
<p>A <strong>function operator</strong> takes a function as input and returns a modified version. Think of them as function decorators.</p>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r">library(purrr)
# compose(): chain functions together (right to left)
round_sqrt <- compose(round, sqrt)
round_sqrt(7)
#> [1] 3
# Left-to-right with the pipe-friendly approach
library(purrr)
add_one_then_double <- compose(\(x) x * 2, \(x) x + 1)
add_one_then_double(5)
#> [1] 12</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># negate(): flip a predicate
library(purrr)
is_even <- \(x) x %% 2 == 0
is_odd <- negate(is_even)
keep(1:10, is_even)
#> [1] 2 4 6 8 10
keep(1:10, is_odd)
#> [1] 1 3 5 7 9</div>
<div class="webr-buttons">
<button class="btn btn-sm btn-primary webr-run-btn" onclick="runWebR(this)">▶ Run</button>
<button class="btn btn-sm btn-default webr-reset-btn" onclick="resetWebR(this)">↺ Reset</button>
</div>
<pre class="webr-output"></pre>
<div class="webr-plot-output"></div>
</div>
</div>
<div class="webr-container">
<div class="webr-code-block">
<div class="webr-editor" data-language="r"># partial(): pre-fill some arguments
library(purrr)
mean_na_rm <- partial(mean, na.rm = TRUE)
x <- c(1, 2, NA, 4, 5)
mean(x)
#> [1] NA
mean_na_rm(x)
#> [1] 3</div>