/
efficient-R.html
1190 lines (942 loc) · 54.7 KB
/
efficient-R.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Writing Efficient R Code</title>
<script type="text/javascript">
window.onload = function() {
var imgs = document.getElementsByTagName('img'), i, img;
for (i = 0; i < imgs.length; i++) {
img = imgs[i];
// center an image if it is the only element of its parent
if (img.parentElement.childElementCount === 1)
img.parentElement.style.textAlign = 'center';
}
};
</script>
<!-- Styles for R syntax highlighter -->
<style type="text/css">
pre .operator,
pre .paren {
color: rgb(104, 118, 135)
}
pre .literal {
color: #990073
}
pre .number {
color: #099;
}
pre .comment {
color: #998;
font-style: italic
}
pre .keyword {
color: #900;
font-weight: bold
}
pre .identifier {
color: rgb(0, 0, 0);
}
pre .string {
color: #d14;
}
</style>
<!-- R syntax highlighter -->
<script type="text/javascript">
var hljs=new function(){function m(p){return p.replace(/&/gm,"&").replace(/</gm,"<")}function f(r,q,p){return RegExp(q,"m"+(r.cI?"i":"")+(p?"g":""))}function b(r){for(var p=0;p<r.childNodes.length;p++){var q=r.childNodes[p];if(q.nodeName=="CODE"){return q}if(!(q.nodeType==3&&q.nodeValue.match(/\s+/))){break}}}function h(t,s){var p="";for(var r=0;r<t.childNodes.length;r++){if(t.childNodes[r].nodeType==3){var q=t.childNodes[r].nodeValue;if(s){q=q.replace(/\n/g,"")}p+=q}else{if(t.childNodes[r].nodeName=="BR"){p+="\n"}else{p+=h(t.childNodes[r])}}}if(/MSIE [678]/.test(navigator.userAgent)){p=p.replace(/\r/g,"\n")}return p}function a(s){var r=s.className.split(/\s+/);r=r.concat(s.parentNode.className.split(/\s+/));for(var q=0;q<r.length;q++){var p=r[q].replace(/^language-/,"");if(e[p]){return p}}}function c(q){var p=[];(function(s,t){for(var r=0;r<s.childNodes.length;r++){if(s.childNodes[r].nodeType==3){t+=s.childNodes[r].nodeValue.length}else{if(s.childNodes[r].nodeName=="BR"){t+=1}else{if(s.childNodes[r].nodeType==1){p.push({event:"start",offset:t,node:s.childNodes[r]});t=arguments.callee(s.childNodes[r],t);p.push({event:"stop",offset:t,node:s.childNodes[r]})}}}}return t})(q,0);return p}function k(y,w,x){var q=0;var z="";var s=[];function u(){if(y.length&&w.length){if(y[0].offset!=w[0].offset){return(y[0].offset<w[0].offset)?y:w}else{return w[0].event=="start"?y:w}}else{return y.length?y:w}}function t(D){var A="<"+D.nodeName.toLowerCase();for(var B=0;B<D.attributes.length;B++){var C=D.attributes[B];A+=" "+C.nodeName.toLowerCase();if(C.value!==undefined&&C.value!==false&&C.value!==null){A+='="'+m(C.value)+'"'}}return A+">"}while(y.length||w.length){var v=u().splice(0,1)[0];z+=m(x.substr(q,v.offset-q));q=v.offset;if(v.event=="start"){z+=t(v.node);s.push(v.node)}else{if(v.event=="stop"){var p,r=s.length;do{r--;p=s[r];z+=("</"+p.nodeName.toLowerCase()+">")}while(p!=v.node);s.splice(r,1);while(r<s.length){z+=t(s[r]);r++}}}}return z+m(x.substr(q))}function j(){function q(x,y,v){if(x.compiled){return}var u;var s=[];if(x.k){x.lR=f(y,x.l||hljs.IR,true);for(var w in x.k){if(!x.k.hasOwnProperty(w)){continue}if(x.k[w] instanceof Object){u=x.k[w]}else{u=x.k;w="keyword"}for(var r in u){if(!u.hasOwnProperty(r)){continue}x.k[r]=[w,u[r]];s.push(r)}}}if(!v){if(x.bWK){x.b="\\b("+s.join("|")+")\\s"}x.bR=f(y,x.b?x.b:"\\B|\\b");if(!x.e&&!x.eW){x.e="\\B|\\b"}if(x.e){x.eR=f(y,x.e)}}if(x.i){x.iR=f(y,x.i)}if(x.r===undefined){x.r=1}if(!x.c){x.c=[]}x.compiled=true;for(var t=0;t<x.c.length;t++){if(x.c[t]=="self"){x.c[t]=x}q(x.c[t],y,false)}if(x.starts){q(x.starts,y,false)}}for(var p in e){if(!e.hasOwnProperty(p)){continue}q(e[p].dM,e[p],true)}}function d(B,C){if(!j.called){j();j.called=true}function q(r,M){for(var L=0;L<M.c.length;L++){if((M.c[L].bR.exec(r)||[null])[0]==r){return M.c[L]}}}function v(L,r){if(D[L].e&&D[L].eR.test(r)){return 1}if(D[L].eW){var M=v(L-1,r);return M?M+1:0}return 0}function w(r,L){return L.i&&L.iR.test(r)}function K(N,O){var M=[];for(var L=0;L<N.c.length;L++){M.push(N.c[L].b)}var r=D.length-1;do{if(D[r].e){M.push(D[r].e)}r--}while(D[r+1].eW);if(N.i){M.push(N.i)}return f(O,M.join("|"),true)}function p(M,L){var N=D[D.length-1];if(!N.t){N.t=K(N,E)}N.t.lastIndex=L;var r=N.t.exec(M);return r?[M.substr(L,r.index-L),r[0],false]:[M.substr(L),"",true]}function z(N,r){var L=E.cI?r[0].toLowerCase():r[0];var M=N.k[L];if(M&&M instanceof Array){return M}return false}function F(L,P){L=m(L);if(!P.k){return L}var r="";var O=0;P.lR.lastIndex=0;var M=P.lR.exec(L);while(M){r+=L.substr(O,M.index-O);var N=z(P,M);if(N){x+=N[1];r+='<span class="'+N[0]+'">'+M[0]+"</span>"}else{r+=M[0]}O=P.lR.lastIndex;M=P.lR.exec(L)}return r+L.substr(O,L.length-O)}function J(L,M){if(M.sL&&e[M.sL]){var r=d(M.sL,L);x+=r.keyword_count;return r.value}else{return F(L,M)}}function I(M,r){var L=M.cN?'<span class="'+M.cN+'">':"";if(M.rB){y+=L;M.buffer=""}else{if(M.eB){y+=m(r)+L;M.buffer=""}else{y+=L;M.buffer=r}}D.push(M);A+=M.r}function G(N,M,Q){var R=D[D.length-1];if(Q){y+=J(R.buffer+N,R);return false}var P=q(M,R);if(P){y+=J(R.buffer+N,R);I(P,M);return P.rB}var L=v(D.length-1,M);if(L){var O=R.cN?"</span>":"";if(R.rE){y+=J(R.buffer+N,R)+O}else{if(R.eE){y+=J(R.buffer+N,R)+O+m(M)}else{y+=J(R.buffer+N+M,R)+O}}while(L>1){O=D[D.length-2].cN?"</span>":"";y+=O;L--;D.length--}var r=D[D.length-1];D.length--;D[D.length-1].buffer="";if(r.starts){I(r.starts,"")}return R.rE}if(w(M,R)){throw"Illegal"}}var E=e[B];var D=[E.dM];var A=0;var x=0;var y="";try{var s,u=0;E.dM.buffer="";do{s=p(C,u);var t=G(s[0],s[1],s[2]);u+=s[0].length;if(!t){u+=s[1].length}}while(!s[2]);if(D.length>1){throw"Illegal"}return{r:A,keyword_count:x,value:y}}catch(H){if(H=="Illegal"){return{r:0,keyword_count:0,value:m(C)}}else{throw H}}}function g(t){var p={keyword_count:0,r:0,value:m(t)};var r=p;for(var q in e){if(!e.hasOwnProperty(q)){continue}var s=d(q,t);s.language=q;if(s.keyword_count+s.r>r.keyword_count+r.r){r=s}if(s.keyword_count+s.r>p.keyword_count+p.r){r=p;p=s}}if(r.language){p.second_best=r}return p}function i(r,q,p){if(q){r=r.replace(/^((<[^>]+>|\t)+)/gm,function(t,w,v,u){return w.replace(/\t/g,q)})}if(p){r=r.replace(/\n/g,"<br>")}return r}function n(t,w,r){var x=h(t,r);var v=a(t);var y,s;if(v){y=d(v,x)}else{return}var q=c(t);if(q.length){s=document.createElement("pre");s.innerHTML=y.value;y.value=k(q,c(s),x)}y.value=i(y.value,w,r);var u=t.className;if(!u.match("(\\s|^)(language-)?"+v+"(\\s|$)")){u=u?(u+" "+v):v}if(/MSIE [678]/.test(navigator.userAgent)&&t.tagName=="CODE"&&t.parentNode.tagName=="PRE"){s=t.parentNode;var p=document.createElement("div");p.innerHTML="<pre><code>"+y.value+"</code></pre>";t=p.firstChild.firstChild;p.firstChild.cN=s.cN;s.parentNode.replaceChild(p.firstChild,s)}else{t.innerHTML=y.value}t.className=u;t.result={language:v,kw:y.keyword_count,re:y.r};if(y.second_best){t.second_best={language:y.second_best.language,kw:y.second_best.keyword_count,re:y.second_best.r}}}function o(){if(o.called){return}o.called=true;var r=document.getElementsByTagName("pre");for(var p=0;p<r.length;p++){var q=b(r[p]);if(q){n(q,hljs.tabReplace)}}}function l(){if(window.addEventListener){window.addEventListener("DOMContentLoaded",o,false);window.addEventListener("load",o,false)}else{if(window.attachEvent){window.attachEvent("onload",o)}else{window.onload=o}}}var e={};this.LANGUAGES=e;this.highlight=d;this.highlightAuto=g;this.fixMarkup=i;this.highlightBlock=n;this.initHighlighting=o;this.initHighlightingOnLoad=l;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="\\b(0[xX][a-fA-F0-9]+|(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.ER="(?![\\s\\S])";this.BE={b:"\\\\.",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE],r:0};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE],r:0};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.inherit=function(r,s){var p={};for(var q in r){p[q]=r[q]}if(s){for(var q in s){p[q]=s[q]}}return p}}();hljs.LANGUAGES.cpp=function(){var a={keyword:{"false":1,"int":1,"float":1,"while":1,"private":1,"char":1,"catch":1,"export":1,virtual:1,operator:2,sizeof:2,dynamic_cast:2,typedef:2,const_cast:2,"const":1,struct:1,"for":1,static_cast:2,union:1,namespace:1,unsigned:1,"long":1,"throw":1,"volatile":2,"static":1,"protected":1,bool:1,template:1,mutable:1,"if":1,"public":1,friend:2,"do":1,"return":1,"goto":1,auto:1,"void":2,"enum":1,"else":1,"break":1,"new":1,extern:1,using:1,"true":1,"class":1,asm:1,"case":1,typeid:1,"short":1,reinterpret_cast:2,"default":1,"double":1,register:1,explicit:1,signed:1,typename:1,"try":1,"this":1,"switch":1,"continue":1,wchar_t:1,inline:1,"delete":1,alignof:1,char16_t:1,char32_t:1,constexpr:1,decltype:1,noexcept:1,nullptr:1,static_assert:1,thread_local:1,restrict:1,_Bool:1,complex:1},built_in:{std:1,string:1,cin:1,cout:1,cerr:1,clog:1,stringstream:1,istringstream:1,ostringstream:1,auto_ptr:1,deque:1,list:1,queue:1,stack:1,vector:1,map:1,set:1,bitset:1,multiset:1,multimap:1,unordered_set:1,unordered_map:1,unordered_multiset:1,unordered_multimap:1,array:1,shared_ptr:1}};return{dM:{k:a,i:"</",c:[hljs.CLCM,hljs.CBLCLM,hljs.QSM,{cN:"string",b:"'\\\\?.",e:"'",i:"."},{cN:"number",b:"\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)"},hljs.CNM,{cN:"preprocessor",b:"#",e:"$"},{cN:"stl_container",b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:a,r:10,c:["self"]}]}}}();hljs.LANGUAGES.r={dM:{c:[hljs.HCM,{cN:"number",b:"\\b0[xX][0-9a-fA-F]+[Li]?\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"number",b:"\\b\\d+(?:[eE][+\\-]?\\d*)?L\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"number",b:"\\b\\d+\\.(?!\\d)(?:i\\b)?",e:hljs.IMMEDIATE_RE,r:1},{cN:"number",b:"\\b\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?i?\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"number",b:"\\.\\d+(?:[eE][+\\-]?\\d*)?i?\\b",e:hljs.IMMEDIATE_RE,r:1},{cN:"keyword",b:"(?:tryCatch|library|setGeneric|setGroupGeneric)\\b",e:hljs.IMMEDIATE_RE,r:10},{cN:"keyword",b:"\\.\\.\\.",e:hljs.IMMEDIATE_RE,r:10},{cN:"keyword",b:"\\.\\.\\d+(?![\\w.])",e:hljs.IMMEDIATE_RE,r:10},{cN:"keyword",b:"\\b(?:function)",e:hljs.IMMEDIATE_RE,r:2},{cN:"keyword",b:"(?:if|in|break|next|repeat|else|for|return|switch|while|try|stop|warning|require|attach|detach|source|setMethod|setClass)\\b",e:hljs.IMMEDIATE_RE,r:1},{cN:"literal",b:"(?:NA|NA_integer_|NA_real_|NA_character_|NA_complex_)\\b",e:hljs.IMMEDIATE_RE,r:10},{cN:"literal",b:"(?:NULL|TRUE|FALSE|T|F|Inf|NaN)\\b",e:hljs.IMMEDIATE_RE,r:1},{cN:"identifier",b:"[a-zA-Z.][a-zA-Z0-9._]*\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"operator",b:"<\\-(?!\\s*\\d)",e:hljs.IMMEDIATE_RE,r:2},{cN:"operator",b:"\\->|<\\-",e:hljs.IMMEDIATE_RE,r:1},{cN:"operator",b:"%%|~",e:hljs.IMMEDIATE_RE},{cN:"operator",b:">=|<=|==|!=|\\|\\||&&|=|\\+|\\-|\\*|/|\\^|>|<|!|&|\\||\\$|:",e:hljs.IMMEDIATE_RE,r:0},{cN:"operator",b:"%",e:"%",i:"\\n",r:1},{cN:"identifier",b:"`",e:"`",r:0},{cN:"string",b:'"',e:'"',c:[hljs.BE],r:0},{cN:"string",b:"'",e:"'",c:[hljs.BE],r:0},{cN:"paren",b:"[[({\\])}]",e:hljs.IMMEDIATE_RE,r:0}]}};
hljs.initHighlightingOnLoad();
</script>
<!-- MathJax scripts -->
<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<style type="text/css">
body, td {
font-family: sans-serif;
background-color: white;
font-size: 13px;
}
body {
max-width: 800px;
margin: auto;
padding: 1em;
line-height: 20px;
}
tt, code, pre {
font-family: 'DejaVu Sans Mono', 'Droid Sans Mono', 'Lucida Console', Consolas, Monaco, monospace;
}
h1 {
font-size:2.2em;
}
h2 {
font-size:1.8em;
}
h3 {
font-size:1.4em;
}
h4 {
font-size:1.0em;
}
h5 {
font-size:0.9em;
}
h6 {
font-size:0.8em;
}
a:visited {
color: rgb(50%, 0%, 50%);
}
pre, img {
max-width: 100%;
}
pre {
overflow-x: auto;
}
pre code {
display: block; padding: 0.5em;
}
code {
font-size: 92%;
border: 1px solid #ccc;
}
code[class] {
background-color: #F8F8F8;
}
table, td, th {
border: none;
}
blockquote {
color:#666666;
margin:0;
padding-left: 1em;
border-left: 0.5em #EEE solid;
}
hr {
height: 0px;
border-bottom: none;
border-top-width: thin;
border-top-style: dotted;
border-top-color: #999999;
}
@media print {
* {
background: transparent !important;
color: black !important;
filter:none !important;
-ms-filter: none !important;
}
body {
font-size:12pt;
max-width:100%;
}
a, a:visited {
text-decoration: underline;
}
hr {
visibility: hidden;
page-break-before: always;
}
pre, blockquote {
padding-right: 1em;
page-break-inside: avoid;
}
tr, img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
@page :left {
margin: 15mm 20mm 15mm 10mm;
}
@page :right {
margin: 15mm 10mm 15mm 20mm;
}
p, h2, h3 {
orphans: 3; widows: 3;
}
h2, h3 {
page-break-after: avoid;
}
}
</style>
</head>
<body>
<h1>Writing Efficient R Code</h1>
<p>Chris Paciorek, Department of Statistics, UC Berkeley</p>
<h1>0) This Tutorial</h1>
<p>This tutorial covers strategies for writing efficient R code by taking advantage of the underlying structure of how R works. In addition it covers tools and strategies for timing and profiling R code.</p>
<p>While some of the strategies covered here are specific to R, many are built on principles that can guide your coding in other languages.</p>
<p>You should be able to work through this tutorial in any working R installation, including through RStudio. However, in many cases the R you are using may not be linked to a fast linear algebra package. </p>
<p>This tutorial assumes you have a working knowledge of R. </p>
<p>Materials for this tutorial, including the R markdown file and associated code files that were used to create this document are available on Github at (<a href="https://github.com/berkeley-scf/tutorial-efficient-R">https://github.com/berkeley-scf/tutorial-efficient-R</a>). You can download the files by doing a git clone from a terminal window on a UNIX-like machine, as follows:</p>
<pre><code class="r">git clone https://github.com/berkeley-scf/tutorial-efficient-R
</code></pre>
<p>To create this HTML document, simply compile the corresponding R Markdown file in R as follows.</p>
<pre><code class="r">Rscript -e "library(knitr); knit2html('efficient-R.Rmd')"
</code></pre>
<p>This tutorial by Christopher Paciorek is licensed under a Creative Commons Attribution 3.0 Unported License.</p>
<h1>1) Background</h1>
<p>In part because R is an interpreted language and in part because R
is very dynamic (objects can be modified essentially arbitrarily after
being created), R can be slow. Hadley Wickham's Advanced R book has
a section called <em>Performance</em> that discusses this in detail. However, there
are a variety of ways that one can write efficient R code.</p>
<p>In general, try to make use of R's built-in functions (including matrix
operations and linear algebra), as these tend to be implemented
internally (i.e., via compiled code in C or Fortran). Sometimes you
can figure out a trick to take your problem and transform it to make
use of the built-in functions.</p>
<p>Before you spend a lot of time trying to make your code go faster,
it's best to first write transparent, easy-to-read code to help avoid
bugs. Then if it doesn't run fast enough, time the different parts of
the code (profiling) to assess where the bottlenecks are. Concentrate
your efforts on those parts of the code. Try out different
specifications, checking that the results are the same as your
original code. And as you gain more experience, you'll get some
intuition for what approaches might improve speed, but even with
experience I find myself often surprised by what matters and what
doesn't.</p>
<p>Section 2 of this document discusses the use of fast linear algebra libraries, Section 3 discusses tools for timing and profiling code, and Section 4 discusses core strategies for writing efficient R code.</p>
<h1>2) Fast linear algebra</h1>
<p>One way to speed up a variety of operations in R (sometimes by as much as an order of magnitude) is to make sure your installation of R uses an optimized BLAS (Basic Linear Algebra Subroutines). The BLAS underlies all linear algebra, including costly calculations such as matrix-matrix multiplication and matrix decompositions such as the SVD and Cholesky decomposition. Some optimized BLAS packages are:</p>
<ul>
<li>Intel's <em>MKL</em></li>
<li><em>OpenBLAS</em></li>
<li>AMD's <em>ACML</em></li>
<li><em>vecLib</em> for Macs</li>
</ul>
<p>To use an optimized BLAS, talk to your systems adminstrator, see <a href="https://cran.r-project.org/manuals.html">Section A.3 of the R Installation and Administration Manual</a>, or see <a href="http://statistics.berkeley.edu/computing/blas">these instructions to use <em>vecLib</em> BLAS on your own Mac</a>.</p>
<p>Any calls to BLAS or to the LAPACK libraries that use BLAS to do higher-level linear algebra calculations will be nearly as fast as if you used C/C++ or Matlab, because R is using the compiled code from the BLAS and LAPACK libraries. </p>
<p>In addition, the BLAS libraries above are threaded – they can use more than one core, and often will do so by default. More details in the <a href="https://github.com/berkeley-scf/tutorial-parallel-basics">SCF tutorial on parallel programming</a>. </p>
<h1>3) Tools for assessing efficiency</h1>
<h2>3.1) Benchmarking</h2>
<p><em>system.time</em> is very handy for comparing the speed of different
implementations. Here's a basic comparison of the time to calculate the row means of a matrix using a for loop compared to the built-in <em>rowMeans</em> function.</p>
<pre><code class="r">n <- 10000
m <- 1000
x <- matrix(rnorm(n*m), nrow = n)
system.time({
mns <- rep(NA, n)
for(i in 1:n) mns[i] <- mean(x[i , ])
})
</code></pre>
<pre><code>## user system elapsed
## 0.251 0.011 0.262
</code></pre>
<pre><code class="r">system.time(rowMeans(x))
</code></pre>
<pre><code>## user system elapsed
## 0.026 0.000 0.026
</code></pre>
<p>In general, <em>user</em> time gives the CPU time spent by R and <em>system</em> time gives the CPU time spent by the kernel (the operating system) on behalf of R. Operations that fall under system time include opening files, doing input or output, starting other processes, etc.</p>
<p>To time code that runs very quickly, you should use the <em>microbenchmark</em>
package. Of course one would generally only care about accurately timing quick calculations if a larger operation does the quick calculation very many times. Here's a comparison of different ways of accessing an element of a dataframe.</p>
<pre><code class="r">library(microbenchmark)
df <- data.frame(vals = 1:3, labs = c('a','b','c'))
microbenchmark(
df[2,1],
df$vals[2],
df[2, 'vals']
)
</code></pre>
<pre><code>## Unit: nanoseconds
## expr min lq mean median uq max neval cld
## df[2, 1] 13976 14559.0 15169.09 14823 15000.0 27324 100 b
## df$vals[2] 748 1063.0 1723.97 1591 1697.5 13343 100 a
## df[2, "vals"] 13834 14413.5 15216.43 14621 14791.0 45620 100 b
</code></pre>
<p><em>microbenchmark</em> is also a good way to compare slower calculations, e.g., doing a crossproduct via <em>crossproduct()</em> compared to “manually”:</p>
<pre><code class="r">library(microbenchmark)
n <- 1000
x <- matrix(rnorm(n^2), n)
microbenchmark(
t(x) %*% x,
crossprod(x),
times = 10)
</code></pre>
<pre><code>## Unit: milliseconds
## expr min lq mean median uq max neval cld
## t(x) %*% x 43.75747 43.79796 52.49518 48.89571 57.60102 78.42165 10 b
## crossprod(x) 19.58690 19.67473 23.19242 19.82202 27.82647 33.67125 10 a
</code></pre>
<p><strong>Challenge</strong>: What is inefficient about the manual approach above?</p>
<p>An alternative that also automates timings and comparisons is the <em>benchmark</em> function from the <em>rbenchmark</em> package, but there's not really a reason to use it when <em>microbenchmark</em> is available.</p>
<pre><code class="r">library(rbenchmark)
# speed of one calculation
benchmark(t(x) %*% x,
crossprod(x),
replications = 10,
columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test elapsed replications
## 2 crossprod(x) 0.275 10
## 1 t(x) %*% x 0.382 10
</code></pre>
<p>In general, it's a good idea to repeat (replicate) your timing, as there is some stochasticity in how fast your computer will run a piece of code at any given moment.</p>
<p>You might also checkout the <em>tictoc</em> package.</p>
<h2>3.2) Profiling</h2>
<p>The <em>Rprof</em> function will show you how much time is spent in
different functions, which can help you pinpoint bottlenecks in your
code. The output from <em>Rprof</em> can be hard to decipher, so you
will probably want to use the <em>proftools</em> package functions, which make use of
<em>Rprof</em> under the hood.</p>
<p>Here's a function that does the linear algebra to find the least squares solution in a linear regression, assuming <code>x</code>
is the matrix of predictors, including a column for the intercept.</p>
<pre><code class="r">lr_slow <- function(y, x) {
xtx <- t(x) %*% x
xty <- t(x) %*% y
inv <- solve(xtx) ## explicit matrix inverse is slow and generally a bad idea numerically
return(inv %*% xty)
}
</code></pre>
<p>Let's run the function with profiling turned on.</p>
<pre><code class="r">## generate random observations and random matrix of predictors
y <- rnorm(5000)
x <- matrix(rnorm(5000*1000), nrow = 5000)
library(proftools)
pd1 <- profileExpr(lr_slow(y, x))
hotPaths(pd1)
</code></pre>
<pre><code>## path total.pct self.pct
## lr_slow 100.00 0.00
## . %*% (<text>:2) 33.65 33.65
## . %*% (<text>:3) 1.92 1.92
## . %*% (<text>:5) 0.96 0.96
## . solve (<text>:4) 38.46 0.00
## . . solve.default 38.46 37.50
## . . . diag 0.96 0.96
## . t (<text>:2) 1.92 0.00
## . . t.default 1.92 1.92
## . t (<text>:3) 23.08 0.00
## . . t.default 23.08 23.08
</code></pre>
<pre><code class="r">hotPaths(pd1, value = 'time')
</code></pre>
<pre><code>## path total.time self.time
## lr_slow 2.08 0.00
## . %*% (<text>:2) 0.70 0.70
## . %*% (<text>:3) 0.04 0.04
## . %*% (<text>:5) 0.02 0.02
## . solve (<text>:4) 0.80 0.00
## . . solve.default 0.80 0.78
## . . . diag 0.02 0.02
## . t (<text>:2) 0.04 0.00
## . . t.default 0.04 0.04
## . t (<text>:3) 0.48 0.00
## . . t.default 0.48 0.48
</code></pre>
<p>The first call to <em>hotPaths</em> shows the percentage of time spent in each call, while the second shows the actual time.</p>
<p>Note the nestedness of the results. For example, essentially all the time spent in <em>solve</em> is actually spent in <em>solve.default</em>. In this case <em>solve</em> is just an S3 generic method that immediately calls the specific method <em>solve.default</em>.</p>
<p>We can see that a lot of time is spent in doing the two crossproducts. So let's try using <em>crossprod</em> to make those steps faster.</p>
<pre><code class="r">lr_medium <- function(y, x) {
xtx <- crossprod(x)
xty <- crossprod(x, y)
inv <- solve(xtx) ## explicit matrix inverse is slow and generally a bad idea numerically
return(inv %*% xty)
}
pd2 <- profileExpr(lr_medium(y, x))
hotPaths(pd2)
</code></pre>
<pre><code>## path total.pct self.pct
## lr_medium 100.00 0.00
## . crossprod (<text>:2) 46.51 46.51
## . crossprod (<text>:3) 4.65 4.65
## . solve (<text>:4) 48.84 0.00
## . . solve.default 48.84 46.51
## . . . diag 2.33 2.33
</code></pre>
<pre><code class="r">hotPaths(pd2, value = 'time')
</code></pre>
<pre><code>## path total.time self.time
## lr_medium 0.86 0.00
## . crossprod (<text>:2) 0.40 0.40
## . crossprod (<text>:3) 0.04 0.04
## . solve (<text>:4) 0.42 0.00
## . . solve.default 0.42 0.40
## . . . diag 0.02 0.02
</code></pre>
<p>First note that this version takes about half the time of the previous one. Second note that a fair amount of time is spent computing the explicit matrix inverse using <em>solve</em>. (There's not much we can do to speed up the <em>crossprod</em> operations, apart from making sure we are using a fast BLAS and potentially a parallelized BLAS.) It's well known that one should avoid computing the explicit inverse if one can avoid it. Here's a faster version that avoids it.</p>
<pre><code class="r">lr_fast <- function(y, x) {
xtx <- crossprod(x)
xty <- crossprod(x, y)
U <- chol(xtx)
tmp <- backsolve(U, xty, transpose = TRUE)
return(backsolve(U, tmp))
}
pd3 <- profileExpr(lr_fast(y, x))
hotPaths(pd3)
</code></pre>
<pre><code>## path total.pct self.pct
## lr_fast 100 0
## . backsolve (<text>:6) 2 2
## . chol (<text>:4) 12 0
## . . chol.default 12 12
## . crossprod (<text>:2) 80 80
## . crossprod (<text>:3) 6 6
</code></pre>
<pre><code class="r">hotPaths(pd3, value = 'time')
</code></pre>
<pre><code>## path total.time self.time
## lr_fast 1.00 0.00
## . backsolve (<text>:6) 0.02 0.02
## . chol (<text>:4) 0.12 0.00
## . . chol.default 0.12 0.12
## . crossprod (<text>:2) 0.80 0.80
## . crossprod (<text>:3) 0.06 0.06
</code></pre>
<p>We can see we get another speedup from that final version of the code. (But beware my earlier caution that if comparing times between implementations, we should have replication.)</p>
<p>You might also check out <em>profvis</em> for an alternative to displaying profiling information
generated by <em>Rprof</em>.</p>
<p>Note that <em>Rprof</em> works by sampling - every little while (the <em>interval</em> argument) during a calculation it finds out what function R is in and saves that information to the file given as the argument to <em>Rprof</em>. So if you try to profile code that finishes really quickly, there's not enough opportunity for the sampling to represent the calculation accurately and you may get spurious results.</p>
<p><em>Warning</em>: <em>Rprof</em> conflicts with threaded linear algebra,
so you may need to set OMP_NUM_THREADS to 1 to disable threaded
linear algebra if you profile code that involves linear algebra. </p>
<h1>4) Strategies for improving efficiency</h1>
<h2>4.1) Pre-allocate memory</h2>
<p>It is very inefficient to iteratively add elements to a vector, matrix,
data frame, array or list (e.g., using <em>c</em>, <em>cbind</em>,
<em>rbind</em>, etc. to add elements one at a time). Instead, create the full object in advance
(this is equivalent to variable initialization in compiled languages)
and then fill in the appropriate elements. The reason is that when
R appends to an existing object, it creates a new copy and as the
object gets big, most of the computation involves the repeated
memory allocation to create the new objects. Here's
an illustrative example, but of course we would not fill a vector
like this using loops because we would in practice use vectorized calculations.</p>
<pre><code class="r">n <- 10000
z <- rnorm(n)
fun_append <- function(vals) {
x <- exp(vals[1])
n <- length(vals)
for(i in 2:n) x <- c(x, exp(vals[i]))
return(x)
}
fun_prealloc <- function(vals) {
n <- length(vals)
x <- rep(as.numeric(NA), n)
for(i in 1:n) x[i] <- exp(vals[i])
return(x)
}
fun_vec <- function(vals) {
x <- exp(vals)
return(x)
}
benchmark(fun_append(z), fun_prealloc(z), fun_vec(z),
replications = 20, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test elapsed replications
## 1 fun_append(z) 2.047 20
## 2 fun_prealloc(z) 0.019 20
## 3 fun_vec(z) 0.004 20
</code></pre>
<p>It's not necessary to use <em>as.numeric</em> above though it saves
a bit of time. <strong>Challenge</strong>: figure out why I have <code>as.numeric(NA)</code>
and not just <code>NA</code>. Hint: what is the type of <code>NA</code>?</p>
<p>In some cases, we can speed up the initialization by initializing a vector of length one and then changing its length and/or dimension, although in many practical
circumstances this would be overkill.</p>
<p>For example, for matrices, start with a vector of length one, change the length, and then change the
dimensions</p>
<pre><code class="r">nr <- nc <- 2000
benchmark(
x <- matrix(as.numeric(NA), nr, nc),
{x <- as.numeric(NA); length(x) <- nr * nc; dim(x) <- c(nr, nc)},
replications = 10, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test
## 2 {\n x <- as.numeric(NA)\n length(x) <- nr * nc\n dim(x) <- c(nr, nc)\n}
## 1 x <- matrix(as.numeric(NA), nr, nc)
## elapsed replications
## 2 0.055 10
## 1 0.147 10
</code></pre>
<p>For lists, we can do this</p>
<pre><code class="r">myList <- vector("list", length = n)
</code></pre>
<h2>4.2) Vectorized calculations</h2>
<p>One key way to write efficient R code is to take advantage of R's
vectorized operations.</p>
<pre><code class="r">n <- 1e6
x <- rnorm(n)
benchmark(
x2 <- x^2,
{ x2 <- as.numeric(NA)
length(x2) <- n
for(i in 1:n) { x2[i] <- x[i]^2 } },
replications = 10, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test
## 2 {\n x2 <- as.numeric(NA)\n length(x2) <- n\n for (i in 1:n) {\n x2[i] <- x[i]^2\n }\n}
## 1 x2 <- x^2
## elapsed replications
## 2 11.231 10
## 1 0.017 10
</code></pre>
<p>So what is different in how R handles the calculations above that
explains the huge disparity in efficiency? The vectorized calculation is being done natively
in C in a for loop. The explicit R for loop involves executing the for
loop in R with repeated calls to C code at each iteration. This involves a lot
of overhead because of the repeated processing of the R code inside the loop. For example,
in each iteration of the loop, R is checking the types of the variables because it's possible
that the types might change, such as in this loop:</p>
<pre><code>x <- 3
for( i in 1:n ) {
if(i == 7) {
x <- 'foo'
}
y <- x^2
}
</code></pre>
<p>You can
usually get a sense for how quickly an R call will pass things along
to C or Fortran by looking at the body of the relevant function(s) being called
and looking for <em>.Primitive</em>, <em>.Internal</em>, <em>.C</em>, <em>.Call</em>,
or <em>.Fortran</em>. Let's take a look at the code for <code>+</code>,
<em>mean.default</em>, and <em>chol.default</em>. </p>
<pre><code class="r">`+`
</code></pre>
<pre><code>## function (e1, e2) .Primitive("+")
</code></pre>
<pre><code class="r">mean.default
</code></pre>
<pre><code>## function (x, trim = 0, na.rm = FALSE, ...)
## {
## if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
## warning("argument is not numeric or logical: returning NA")
## return(NA_real_)
## }
## if (na.rm)
## x <- x[!is.na(x)]
## if (!is.numeric(trim) || length(trim) != 1L)
## stop("'trim' must be numeric of length one")
## n <- length(x)
## if (trim > 0 && n) {
## if (is.complex(x))
## stop("trimmed means are not defined for complex data")
## if (anyNA(x))
## return(NA_real_)
## if (trim >= 0.5)
## return(stats::median(x, na.rm = FALSE))
## lo <- floor(n * trim) + 1
## hi <- n + 1 - lo
## x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
## }
## .Internal(mean(x))
## }
## <bytecode: 0x5646e07c69f0>
## <environment: namespace:base>
</code></pre>
<pre><code class="r">chol.default
</code></pre>
<pre><code>## function (x, pivot = FALSE, LINPACK = FALSE, tol = -1, ...)
## {
## if (!missing(LINPACK))
## stop("the LINPACK argument has been defunct since R 3.1.0")
## if (is.complex(x))
## stop("complex matrices not permitted at present")
## .Internal(La_chol(as.matrix(x), pivot, tol))
## }
## <bytecode: 0x5646e34aa168>
## <environment: namespace:base>
</code></pre>
<p>Many R functions allow you to pass in vectors, and operate on those
vectors in vectorized fashion. So before writing a for loop, look
at the help information on the relevant function(s) to see if they
operate in a vectorized fashion. Functions might take vectors for one or more of their arguments.
Here we see that <code>nchar</code> is vectorized and that various arguments to <code>substring</code> can be vectors.</p>
<pre><code class="r">address <- c("Four score and seven years ago our fathers brought forth",
" on this continent, a new nation, conceived in Liberty, ",
"and dedicated to the proposition that all men are created equal.")
nchar(address)
</code></pre>
<pre><code>## [1] 56 56 64
</code></pre>
<pre><code class="r"># use a vector in the 2nd and 3rd arguments, but not the first
startIndices = seq(1, by = 3, length = nchar(address[1])/3)
startIndices
</code></pre>
<pre><code>## [1] 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55
</code></pre>
<pre><code class="r">substring(address[1], startIndices, startIndices + 1)
</code></pre>
<pre><code>## [1] "Fo" "r " "co" "e " "nd" "se" "en" "ye" "rs" "ag" " o" "r " "at" "er" " b"
## [16] "ou" "ht" "fo" "th"
</code></pre>
<p><strong>Challenge</strong>: Consider the chi-squared statistic involved in
a test of independence in a contingency table:
\[
\chi^{2}=\sum_{i}\sum_{j}\frac{(y_{ij}-e_{ij})^{2}}{e_{ij}},\,\,\,\, e_{ij}=\frac{y_{i\cdot}y_{\cdot j}}{y_{\cdot\cdot}}
\]
where \(y_{i\cdot}=\sum_{j}y_{ij}\) and \(y_{\cdot j} = \sum_{i} y_{ij}\). Write this in a vectorized way
without any loops. Note that 'vectorized' calculations also work
with matrices and arrays.</p>
<p>Vectorized operations can sometimes be faster than built-in functions
(note here the <em>ifelse</em> is notoriously slow),
and clever vectorized calculations even better, though sometimes the
code is uglier. Here's an example of setting all negative values in a
vector to zero.</p>
<pre><code class="r">x <- rnorm(1000000)
benchmark(
truncx <- ifelse(x > 0, x, 0),
{truncx <- x; truncx[x < 0] <- 0},
truncx <- x * (x > 0),
replications = 10, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test elapsed replications
## 1 truncx <- ifelse(x > 0, x, 0) 1.571 10
## 2 {\n truncx <- x\n truncx[x < 0] <- 0\n} 0.164 10
## 3 truncx <- x * (x > 0) 0.083 10
</code></pre>
<p>Additional tips:</p>
<ul>
<li>If you do need to loop over dimensions of a matrix or array, if possible
loop over the smallest dimension and use the vectorized calculation
on the larger dimension(s). For example if you have a 10000 by 10 matrix, try to set
up your problem so you can loop over the 10 columns rather than the 10000 rows.</li>
<li>In general, looping over columns is likely to be faster than looping over rows
given R's column-major ordering (matrices are stored in memory as a long array in which values in a column are adjacent to each other) (see more in Section 4.6 on the cache).</li>
<li>You can use direct arithmetic operations to add/subtract/multiply/divide
a vector by each column of a matrix, e.g. <code>A*b</code> does element-wise multiplication of
each column of <em>A</em> by a vector <em>b</em>. If you need to operate
by row, you can do it by transposing the matrix. </li>
</ul>
<p>Caution: relying on R's recycling rule in the context of vectorized
operations, such as is done when direct-multiplying a matrix by a
vector to scale the rows relative to each other, can be dangerous as the code is not transparent
and poses greater dangers of bugs. In some cases you may want to
first write the code transparently and
then compare the more efficient code to make sure the results are the same. It's also a good idea to comment your code in such cases.</p>
<h2>4.3) Using <em>apply</em> and specialized functions</h2>
<p>Historically, another core efficiency strategy in R has been to use the <em>apply</em> functionality (e.g., <code>apply</code>, <code>sapply</code>, <code>lapply</code>, <code>mapply</code>, etc.).</p>
<h3>Some faster alternatives to <code>apply</code></h3>
<p>Note that even better than <em>apply</em> for calculating sums or means of columns
or rows (it also can be used for arrays) is {row,col}{Sums,Means}.</p>
<pre><code class="r">n <- 3000; x <- matrix(rnorm(n * n), nr = n)
benchmark(
out <- apply(x, 1, mean),
out <- rowMeans(x),
replications = 10, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test elapsed replications
## 1 out <- apply(x, 1, mean) 1.562 10
## 2 out <- rowMeans(x) 0.232 10
</code></pre>
<p>We can 'sweep' out a summary statistic, such as subtracting
off a mean from each column, using <em>sweep</em></p>
<pre><code class="r">system.time(out <- sweep(x, 2, STATS = colMeans(x), FUN = "-"))
</code></pre>
<pre><code>## user system elapsed
## 0.138 0.009 0.147
</code></pre>
<p>Here's a trick for doing the sweep based on vectorized calculations, remembering
that if we subtract a vector from a matrix, it subtracts each element
of the vector from all the elements in the corresponding ROW. Hence the
need to transpose twice. </p>
<pre><code class="r">system.time(out2 <- t(t(x) - colMeans(x)))
</code></pre>
<pre><code>## user system elapsed
## 0.293 0.011 0.303
</code></pre>
<pre><code class="r">identical(out, out2)
</code></pre>
<pre><code>## [1] TRUE
</code></pre>
<h3>Are <em>apply</em>, <em>lapply</em>, <em>sapply</em>, etc. faster than loops?</h3>
<p>Using <em>apply</em> with matrices and versions of <em>apply</em> with lists or vectors (e.g., <code>lapply</code>, <code>sapply</code>) may or may not be faster
than looping but generally produces cleaner code.</p>
<p>Whether looping and use of apply variants is slow will depend in part on whether a substantial part of the work is
in the overhead involved in the looping or in the time required by the function
evaluation on each of the elements. If you're worried about speed,
it's a good idea to benchmark the <em>apply</em> variant against looping.</p>
<p>Here's an example where <em>apply</em> is not faster than a loop. Similar
examples can be constructed where <em>lapply</em> or <em>sapply</em> are not faster
than writing a loop. </p>
<pre><code class="r">n <- 500000; nr <- 10000; nCalcs <- n/nr
mat <- matrix(rnorm(n), nrow = nr)
times <- 1:nr
system.time(
out1 <- apply(mat, 2, function(vec) {
mod = lm(vec ~ times)
return(mod$coef[2])
}))
</code></pre>
<pre><code>## user system elapsed
## 0.087 0.000 0.086
</code></pre>
<pre><code class="r">system.time({
out2 <- rep(NA, nCalcs)
for(i in 1:nCalcs){
out2[i] = lm(mat[ , i] ~ times)$coef[2]
}
})
</code></pre>
<pre><code>## user system elapsed
## 0.087 0.000 0.087
</code></pre>
<p>And here's an example, where (unlike the previous example) the core computation is very fast, so we might expect the overhead of looping to be important. I believe that in old versions of R the <em>sapply</em> in this example was faster than looping in R, but that doesn't seem to be the case currently.
I think this may be related to various somewhat recent improvements in R's handling of loops, possibly including the use of the byte compiler.</p>
<pre><code class="r">z <- rnorm(1e6)
fun_loop <- function(vals) {
x <- as.numeric(NA)
n <- length(vals)
length(x) <- n
for(i in 1:n) x[i] <- exp(vals[i])
return(x)
}
fun_sapply <- function(vals) {
x <- sapply(vals, exp)
return(x)
}
fun_vec <- function(vals) {
x <- exp(vals)
return(x)
}
benchmark(fun_loop(z), fun_sapply(z), fun_vec(z),
replications = 10, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test elapsed replications
## 1 fun_loop(z) 0.946 10
## 2 fun_sapply(z) 4.792 10
## 3 fun_vec(z) 0.113 10
</code></pre>
<p>You'll notice if you look at the R code for <em>lapply</em> (<em>sapply</em> just calls <em>lapply</em>) that it calls directly out to C code, so the for loop is executed in compiled code. However, the code being executed at each iteration is still R code, so there is still all the overhead of the R interpreter. </p>
<pre><code class="r">print(lapply)
</code></pre>
<pre><code>## function (X, FUN, ...)
## {
## FUN <- match.fun(FUN)
## if (!is.vector(X) || is.object(X))
## X <- as.list(X)
## .Internal(lapply(X, FUN))
## }
## <bytecode: 0x5646de5809b0>
## <environment: namespace:base>
</code></pre>
<h2>4.4) Matrix algebra efficiency</h2>
<p>Often calculations that are not explicitly linear algebra calculations
can be done as matrix algebra. If our R installation has a fast (and possibly parallelized) BLAS, this allows our calculation to take advantage of it.</p>
<p>For example, we can sum the rows of a matrix by multiplying by a vector of ones. Given the extra computation involved in actually multiplying each number by one, it's surprising that this is faster than using R's heavily optimized <em>rowSums</em> function. </p>
<pre><code class="r">mat <- matrix(rnorm(500*500), 500)
benchmark(apply(mat, 1, sum),
mat %*% rep(1, ncol(mat)),
rowSums(mat),
replications = 10, columns=c('test', 'elapsed', 'replications'))
</code></pre>
<pre><code>## test elapsed replications
## 1 apply(mat, 1, sum) 0.033 10
## 2 mat %*% rep(1, ncol(mat)) 0.003 10
## 3 rowSums(mat) 0.006 10
</code></pre>
<p>On the other hand, big matrix operations can be slow. <strong>Challenge</strong>: Suppose you
want a new matrix that computes the differences between successive
columns of a matrix of arbitrary size. How would you do this as matrix
algebra operations? It's possible to write it as multiplying the matrix
by another matrix that contains 0s, 1s, and -1s in appropriate places.
Here it turns out that the
<em>for</em> loop is much faster than matrix multiplication. However,
there is a way to do it faster as matrix direct subtraction. </p>
<h3>Order of operations and efficiency</h3>
<p>When doing matrix algebra, the order in which you do operations can
be critical for efficiency. How should I order the following calculation?</p>
<pre><code class="r">n <- 5000
A <- matrix(rnorm(5000 * 5000), 5000)
B <- matrix(rnorm(5000 * 5000), 5000)
x <- rnorm(5000)
system.time(
res1 <- A %*% B %*% x
)
</code></pre>
<pre><code>## user system elapsed
## 22.203 5.396 3.966
</code></pre>
<pre><code class="r">system.time(
res2 <- A %*% (B %*% x)
)
</code></pre>
<pre><code>## user system elapsed
## 0.209 0.000 0.209
</code></pre>
<p>Why is the second order much faster?</p>
<h3>Avoiding unnecessary operations</h3>
<p>We can use the matrix direct product (i.e., <code>A*B</code>) to do
some manipulations much more quickly than using matrix multiplication.
<strong>Challenge</strong>: How can I use the direct product to find the trace
of a matrix, \(XY\)? </p>
<p>Finally, when working with diagonal matrices, you can generally get much faster results by being smart. The following operations: \(X+D\), \(DX\), \(XD\)
are mathematically the sum of two matrices and products of two matrices.
But we can do the computation without using two full matrices.
<strong>Challenge</strong>: How?</p>
<pre><code class="r">n <- 1000
X <- matrix(rnorm(n^2), n)
diagvals <- rnorm(n)
D = diag(diagvals)
# the following lines are very inefficient
summedMat <- X + D
prodMat1 <- D %*% X
prodMat2 <- X %*% D
# How can we do each of those operations much more quickly?
</code></pre>
<p>More generally, sparse matrices and structured matrices (such as block
diagonal matrices) can generally be worked with MUCH more efficiently
than treating them as arbitrary matrices. The R packages <em>spam</em> (for arbitrary
sparse matrices), <em>bdsmatrix</em> (for block-diagonal matrices),
and <em>Matrix</em> (for a variety of sparse matrix types) can help, as can specialized code available in other languages,
such as C and Fortran packages.</p>
<h2>4.5) Fast mapping/lookup tables</h2>
<p>Sometimes you need to map between two vectors. E.g.,
\(y_{i}\sim\mathcal{N}(\mu_{j[i]},\sigma^{2})\)
is a basic ANOVA type structure, where multiple observations
are associated with a common mean, \(\mu_j\), via the <code>j[i]</code> mapping. </p>
<p>How can we quickly look up the mean associated with each observation?
A good strategy is to create a vector, <em>grp</em>, that gives a numeric
mapping of the observations to their cluster, playing the role of <code>j[i]</code> above. Then you can access
the \(\mu\) value relevant for each observation as: <code>mus[grp]</code>. This requires
that <em>grp</em> correctly map to the right elements of <em>mus</em>.</p>