-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
2083 lines (1636 loc) · 53.9 KB
/
index.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>
<title>R Intro Part 4</title>
<meta charset="utf-8">
<meta name="description" content="R Intro Part 4">
<meta name="author" content="Ilan Man">
<meta name="generator" content="slidify" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<link rel="stylesheet" href="libraries/frameworks/io2012/css/default.css" media="all" >
<link rel="stylesheet" href="libraries/frameworks/io2012/phone.css"
media="only screen and (max-device-width: 480px)" >
<link rel="stylesheet" href="libraries/frameworks/io2012/css/slidify.css" >
<link rel="stylesheet" href="libraries/highlighters/highlight.js/css/tomorrow.css" />
<base target="_blank"> <!-- This amazingness opens all links in a new tab. -->
<script data-main="libraries/frameworks/io2012/js/slides"
src="libraries/frameworks/io2012/js/require-1.0.8.min.js">
</script>
<link rel="stylesheet" href = "assets/css/ribbons.css">
</head>
<body style="opacity: 0">
<slides class="layout-widescreen">
<!-- LOGO SLIDE -->
<!-- END LOGO SLIDE -->
<!-- TITLE SLIDE -->
<!-- Should I move this to a Local Layout File? -->
<slide class="title-slide segue nobackground">
<hgroup class="auto-fadein">
<h1>R Intro Part IV</h1>
<h2>Data structures and functions</h2>
<p>Ilan Man<br/>Strategy Operations @ Squarespace</p>
</hgroup>
</slide>
<!-- SLIDES -->
<slide class="" id="slide-1" style="background:;">
<hgroup>
<h2>Agenda</h2>
</hgroup>
<article>
<ol>
<li>R intro</li>
<li>Data structures</li>
<li>Control structures</li>
<li>Functions</li>
<li>Commonly used built in functions</li>
<li>String manipulation</li>
<li>Miscellaneous Tips and tricks</li>
</ol>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-2" style="background:;">
<hgroup>
<h2>R Intro</h2>
</hgroup>
<article>
<h1>Background</h1>
<p><space></p>
<ul>
<li>Derivative of S language, developed at Bell Laboratories by John Chambers</li>
<li>R was created by two statisticians at the University of Auckland, New Zealand</li>
<li>R is written in C, Fortran and R</li>
<li>Open source (Revolution Analytics offers commerical software)</li>
<li>Originally command line, but graphical interfaces (including RStudio and Rattle) becoming new norm</li>
<li>Very popular, especially among academics and statisticians</li>
<li>Intepreted language - easier to write code, but slower computations</li>
<li>Packages available to speed up R code - <a href="http://cran.r-project.org/web/packages/Rcpp/index.html"><code>Rcpp</code></a>, <a href="http://cran.r-project.org/web/packages/ff/index.html"><code>ff</code></a>, <a href="http://cran.r-project.org/web/packages/snow/snow.pdf"><code>snow</code></a>, <a href="http://stat.ethz.ch/R-manual/R-devel/library/parallel/doc/parallel.pdf"><code>parallel</code></a></li>
<li>R holds all data in RAM. Problematic for large data sets</li>
<li>R is excellent for prototyping</li>
<li><code>?help</code> -> use this to get help. <code>?</code> is easily the most useful function in R.</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-3" style="background:;">
<hgroup>
<h2>R Intro</h2>
</hgroup>
<article>
<h1>Background</h1>
<p><space></p>
<ul>
<li>Installing packages</li>
</ul>
<pre><code class="r">install.packages('ggplot2') ## do this once only
require('ggplot2') ## do this every time you load up an R session
library() ## shows you every package in your standard package location
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-4" style="background:;">
<hgroup>
<h2>R Intro</h2>
</hgroup>
<article>
<h1>Styling</h1>
<p><space></p>
<ul>
<li><a href="http://cran.r-project.org/web/packages/rockchalk/vignettes/Rstyle.pdf">CRAN</a> and <a href="http://google-styleguide.googlecode.com/svn/trunk/Rguide.xml">Google</a> style guide</li>
<li><p><a href="https://docs.google.com/document/d/1esDVxyWvH8AsX-VJa-8oqWaHLs4stGlIbk8kLc5VlII/edit">R Coding convention</a> is another resource</p></li>
<li><p>Use <code><-</code> NOT <code>=</code> for assignment</p></li>
<li><p>Spaces between operators like <code>+</code>, <code>%*%</code>, <code><</code>, <code>></code> and after closing brackets <code>)</code>, <code>}</code></p></li>
<li><p>Don't write functions named <code>rep()</code>, <code>sample()</code>, <code>plot()</code> or any other built-in R names</p></li>
<li><p><code>c</code> should not be used for any variable names</p></li>
<li><p><code>i</code> and <code>j</code> should only be used in loops, conditionals, etc...</p></li>
<li><p>Use camel case for functions: <code>myFirstFunction()</code> is better than <code>my.first.function()</code></p></li>
<li><p>Use <code>'hello'</code> or <code>"hello"</code> for strings, but be consistent.</p></li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-5" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<ol>
<li>Vectors</li>
<li>Matrices</li>
<li>Lists</li>
<li>Data.frames</li>
<li>Factors</li>
</ol>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-6" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectors</h1>
<p><space></p>
<ul>
<li>Fundamental R data type: Everything is a vector in R (including scalars)</li>
<li>Vector elements must be of the same type, or <code>mode</code> in R. Known as atomic.</li>
<li>Common ways to initialize a vector</li>
</ul>
<pre><code class="r">x <- c(1,2,3,4,5,6,7,8,9,10) ## vector from 1 to 10 - class numeric
x <- 1:10 ## alternative - class integer
x <- seq(from=1,to=10,by=1) ## alternative - class numeric
n <- 10
x <- numeric(n)
for (i in 1:n) x[i] <- i ## as n gets large, this is very slow (compared to the alternatives)
x <- numeric(0)
for (i in 1:n) x <- c(x,i) ## preferred vs. above
## to the extent possible, provide the size of your object when
## initializing it
</code></pre>
<ul>
<li>Six atomic vector types:
<ul> <code>logical</code>, <code>character</code>, <code>integer</code>, <code>double</code>, <code>complex</code>, <code>raw</code></ul></li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-7" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectors</h1>
<p><space></p>
<ul>
<li>Vectors obviate need for loops (most of the time!)</li>
</ul>
<pre><code class="r">x <- seq(from = 1, to = 10, by = 1)
y <- 0
for (i in c(1:length(x))) y[i] <- x[i] * 5
print(y)
</code></pre>
<pre><code> [1] 5 10 15 20 25 30 35 40 45 50
</code></pre>
<pre><code class="r">## alternatively....
y <- x * 5
print(y)
</code></pre>
<pre><code> [1] 5 10 15 20 25 30 35 40 45 50
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-8" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vector Indexing</h1>
<p><space></p>
<ul>
<li>Important, but only if you like using vectors. And R.</li>
<li>Indexing begins at 1, not 0.</li>
<li>Can index a vector by name, if elements are named.</li>
</ul>
<pre><code class="r">x <- 1:10
x[ c( 1:5 , 8:10 ) ]
[1] 1 2 3 4 5 8 9 10
x[ c(TRUE , FALSE) ] ## recycling - common R feature. R will not give you a warning!
[1] 1 3 5 7 9 ## very useful, but make sure you are comparing vectors of same length
x > 5 ## Boolean vector. mode = "logical"
[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
any(x > 5)
[1] TRUE
all(x < 8)
[1] FALSE
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-9" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectorized Operations</h1>
<p><space></p>
<ul>
<li>Easiest way to acheive speed in R - apply a function to a vector</li>
</ul>
<pre><code class="r">f <- function(a, b) return(a^b)
f(x, 2)
</code></pre>
<pre><code> [1] 1 4 9 16 25 36 49 64 81 100
</code></pre>
<ul>
<li>Even operators such as <code>+</code>, <code>-</code>, <code>*</code> are functions</li>
</ul>
<pre><code class="r">"*"(x,5) ## returns 5 * x[1], 5 * x[2], ...
'['(x, x > 5 ) ## returns vector of values where x[1] > 5, x[2] > 5, ..., x[10] > 5 is TRUE
ifelse(x < 5, x^2, 0) ## if (condition) { do something } else { do something else }
[1] 1 4 9 16 0 0 0 0 0 0
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-10" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectorized Operations</h1>
<p><space></p>
<ul>
<li>When coming from a different language, probably best NOT to translate code verbatim</li>
<li>Loops are your friend in C. In R, loops are like a bad friend - timeconsuming at best.</li>
<li>Under the hood, a vectorized operation is running a loop - in C. Much faster than in R.</li>
<li>Vectorization also provides clarity (but don't get carried away one-lining everthing)</li>
</ul>
<pre><code class="r">logsum <- 0
x <- seq(100,1000000,by=10)
for (i in 1:length(x)){
logsum <- logsum + log(x[i])
}
logsum
[1] 1281524 ## this calculation takes about 0.17 seconds
# R translation
logsum <- sum(log(x)) ## this calculation takes about 0.002 seconds.
[1] 1281524
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-11" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectorized Operations</h1>
<p><space></p>
<ul>
<li>Be careful when thinking you are vectorizing</li>
<li>Many R functions take a function as an argument</li>
<li><code>sum</code>, <code>max</code>, <code>min</code>, ... are exceptions</li>
</ul>
<pre><code class="r">mean(1,3,2)
[1] 1 ## huh??
mean(c(1,3,2))
[1] 2 ## that's better
max(1,3,2)
[1] 3
</code></pre>
<ul>
<li>Vectorization might not work when the current iteration depends on the previous (think $ \sum \sum $)</li>
<li>Try to put code outside of loops when possible</li>
<li>Use built-in functions such as <code>rowSums(x)</code> instead of <code>apply(x,1,sum)</code>...more on this later!</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-12" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectors: <code>NA</code> and <code>NULL</code></h1>
<p><space></p>
<ul>
<li><code>NA</code> appears often in messy data, especially when a value doesn't exist</li>
<li>R will attempt to calculate <code>NA</code>, and therefore return <code>NA</code></li>
<li>If R sees <code>NULL</code>, it skips it. <code>NULL</code> is non existant. Yet it exists as a <code>NULL</code>. ?philosophy.</li>
</ul>
<pre><code class="r">x <- c(5, 10, NA, 20, 25)
mean(x)
[1] NA
is.na(x) ## commonly used when cleaning data sets
[1] FALSE FALSE TRUE FALSE FALSE
mean(x,na.rm=TRUE) ## 15
x <- c(5,10,NULL,20,25)
mean(x) ## 15
length(NA) ## NA is a logical constant of length 1
[1] 1
length(NULL) ## NULL does not take any value. By definition, it's undefined
[1] 0 ## ?philosphy
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-13" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vector Filtering</h1>
<p><space></p>
<ul>
<li>Extremely useful for quick data analysis. Similar to indexing.</li>
</ul>
<pre><code class="r">x <- 1:10
x[ x > 5 ] ## What's happening here?
</code></pre>
<ul>
<li><code>x > 5</code> is a function call to <code>">"(a,b)</code> which returns <code>TRUE</code> or <code>FALSE</code> on every element of vector <code>x</code>. </li>
<li>Output of <code>x > 5</code> is <code>logical</code> vector. And when used as an index on <code>x</code>...</li>
</ul>
<pre><code class="r">x[c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE)]
</code></pre>
<pre><code>[1] 6 7 8 9 10
</code></pre>
<p>...returns elements of <code>x</code> that are <code>TRUE</code></p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-14" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vector Filtering</h1>
<p><br>
Common filtering functions include:</p>
<pre><code class="r">subset(x, x > 5) ## [1] 6 7 8 9 10
which(x > 5) ## [1] 6 7 8 9 10
4%in%x ## [1] TRUE
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-15" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Vectors: Summary</h1>
<p><space></p>
<ul>
<li>Everything in R is a vector</li>
<li>All elements are of one type, <code>atomic</code></li>
<li>Vectorize whenever possible</li>
<li>Filtering and indexing are important concepts</li>
<li>Recycling - useful but note that R will not give you an error message</li>
<li><code>seq()</code>, <code>rep()</code>, <code>sample()</code>, <code>runif()</code></li>
<li><code>any()</code>, <code>all()</code>, <code>which()</code>, <code>subset()</code>, <code>%in%</code></li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-16" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Exercise!</h1>
<p><br>
Compute the following:</p>
<p>a) \(\large \sum_{i=1}^{500} \ln{(i^{2})} + \frac{2}{i}\)</p>
<p>b) \(\large \frac{1}{n}\sum_{i=1}^{n} (\bar{X} - X_{i})^{2}\), where X ~ Normal(5,100) and n = 1000
<br><br>
Hint:</br></p>
<pre><code class="r">?rnorm
</code></pre>
<p>c) \(\large \frac{1}{n}\sum_{i=1}^{n} (\bar{X} - X_{i})(\bar{Y} - Y_{i})\), where X ~ Poisson with lambda of 2, Y ~ Exponential with a rate of 1, and n = 1000</p>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-17" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Matrices</h1>
<p><space></p>
<ul>
<li>Like vectors with two additional attributes: rows and columns</li>
<li>Column-major order: insert values in first column, going down, then continuing to second column, going down, as so on</li>
</ul>
<pre><code class="r">x <- matrix(seq(1, 6, by = 1), nrow = 3, ncol = 2) ## 3 by 2 matrix
print(x)
</code></pre>
<pre><code> [,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
</code></pre>
<pre><code class="r">x <- matrix( seq(1,6,by=1), nrow=3) ## same as above
x <- matrix( seq(1,6,by=1), nrow=3, byrow=TRUE) ## row-major order
x <- matrix( seq(1,6,by=1), nrow=4) ## is this ok?
x <- matrix( seq(1,6,by=1), nrow=3, ncol=3) ## is this ok?
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-18" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Matrix operations</h1>
<p><space></p>
<pre><code class="r">x <- matrix(seq(1,9),nrow=3,ncol=3)
x + 5
x * 2
t(x) ## transpose
x %*% x ## inner product
crossprod(x,x) ## cross product of x and x
x * x ## element-wise product
diag(x) ## diagonal components - identity matrix
det(x) ## determinant
eigen(x) ## list of eigenvalues and eigenvectors
</code></pre>
<ul>
<li>Remember your linear algebra!</li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-19" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Matrix indexing and filtering</h1>
<p><space></p>
<pre><code class="r">x[2,1] ## second row, first column
x[,1] ## all rows, first column. Vector form, not matrix.
x[,] ## all rows, all columns. Same as print(x), or just x.
x[-1,] ## remove first row. Negative indexing.
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-20" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Matrix class</h1>
<p><space></p>
<pre><code class="r">x <- matrix( c(1:9), nrow=3, ncol=3)
class(x) ## matrix
y <- x[1,] ## 3 element vector
class(y) ## integer
attributes(y) ## returns NULL
y <- x[1,, drop=FALSE]
class(y) ## matrix
attributes(y) ## 1 by 3 matrix
colnames(x) <- c( 'first col' , 'second col' , 'third col' )
rownames(x) <- c( 'row 1' , 'row 2' , 'row 3' )
</code></pre>
<ul>
<li>Higher dimension matrices also possible, <code>arrays</code></li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-21" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Exercise!</h1>
<p><space></p>
<pre><code class="r">a)
x <- matrix(rep(c(1,3,-1,2),5),ncol=4)
(i) What is returned by the following? Do it by hand before typing it in.
mean(x[ x[1,] > 1, c(1:2) ])
(ii) Find the column in x which has the largest total.
b)
y <- matrix(c(c(1,2,4,8),c(2,3,-1,-7),c(0,5,12,-4),c(3,4,5,0)),ncol=4)
(i) Calculate the trace of y.
(ii) Replace each element of the 3rd column with the median of the elements of the first, second and
fourth columns for the same row.
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-22" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Lists</h1>
<p><space></p>
<ul>
<li>Combine objects of different types. Can have different <code>modes</code>.</li>
<li>Forms basis for <code>data.frames</code></li>
<li>Vectors, matrices cannot be broken down into smaller components, hence atomic.</li>
<li>Lists can be broken down - known as recursive vectors.</li>
</ul>
<pre><code class="r">x <- list(title = "R presentation", date = format(as.POSIXlt(Sys.time(), "EDT"),
"%m %d %Y"), num_attendees = 10)
</code></pre>
<pre><code>Warning: unknown timezone 'EDT'
</code></pre>
<pre><code class="r">print(x)
</code></pre>
<pre><code>$title
[1] "R presentation"
$date
[1] "07 09 2014"
$num_attendees
[1] 10
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-23" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Lists</h1>
<p><space></p>
<ul>
<li>Accessing <code>list</code> components</li>
</ul>
<pre><code class="r">## one bracket - [ - returns a list type
x[1]
</code></pre>
<pre><code>$title
[1] "R presentation"
</code></pre>
<pre><code class="r">## two brackets - [[ - returns the actual element, in this case a character
x[[1]]
x$title
x[['title']]
[1] "R presentation"
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-24" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Lists</h1>
<p><space></p>
<ul>
<li>Accessing <code>list</code> components and values</li>
</ul>
<pre><code class="r">names(x)
[1] "title" "date" "num_attendees"
unlist(x) ## flattens the list into a character vector
pres_1 <- format(as.POSIXlt(Sys.Date(),"EDT"),"%m %d %Y")
pres_2 <- format(as.POSIXlt(Sys.Date()+30,"EDT"),"%m %d %Y")
x <- list(title='1st R presentation', date=pres_1, num_attendees=10)
y <- list(title='2nd R presentation', date=pres_2, num_attendees=20)
z <- list(x,y) ## list of lists
## z[[1]][1] is equivalent to x
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-25" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Lists</h1>
<p><space></p>
<ul>
<li>The result of most statistical operations in R return a <code>list</code></li>
<li>Knowing how to manipulate lists is important</li>
</ul>
<pre><code class="r">n <- 100
x <- rnorm(n, mean = 0, sd = 1) ## sample of 100 random standard normal variables
y <- 1 - 2 * x + rnorm(n)
f <- y ~ x ## y ~ x is a formula object
r <- lm(f) ## r is linear model object, i.e. linear regression
## the function str() - "structure"" - is VERY useful in exploratory data analysis
## structure of r is a bunch of lists
str(r)
r$coeff
r$residuals
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-26" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Data Frames</h1>
<p><space></p>
<ul>
<li>The most useful object in R for data analysis</li>
<li>Like a matrix of lists, of equal length</li>
<li>Many R functions and packages assume input is in the form of a <code>data.frame</code></li>
<li><p>Every CSV or Text file you read in is a <code>data.frame</code>, i.e. most real data comes in the form of a <code>data.frame</code></p></li>
<li><p>Creating Data Frames</p></li>
</ul>
<pre><code class="r">z <- data.frame() ## data frame with 0 columns and 0 rows
y <- data.frame(col1 = c(1, 2), col2 = c("a", "b"), row.names = c("row1", "row2"))
print(y)
</code></pre>
<pre><code> col1 col2
row1 1 a
row2 2 b
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-27" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Data Frames</h1>
<p><space></p>
<pre><code class="r">x <- data.frame(matrix( sample(c(50:100), size=12, replace=TRUE), nrow=6, ncol=2))
## return first column
x[,1] ## type is vector
x$X1 ## type is vector
x[1] ## type data.frame.
x['X1'] ## type data.frame
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-28" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Data Frames</h1>
<p><space></p>
<ul>
<li>Helpful <code>data.frame</code> functions</li>
</ul>
<pre><code class="r">x <- x[-6,] ## remove rows or columns with a "-" sign. Like negative indexing.
y <- data.frame(names = c("dave","jenny","scott","mary","harry") )
z <- cbind(y, x) ## column bind. Can be used on matrices too.
## if you cbind two vectors you get a matrix, NOT data.frame
## alternatively you can create columns implicitly
x$names <- c("dave" ,"jenny" ,"scott" ,"mary" ,"harry")
w <- data.frame(names="megan", X1=82, X2=85)
z <- rbind(z, w) ## row bind
## make sure number of elements in row, column are consistent
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-29" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Data Frames</h1>
<p><space></p>
<pre><code class="r">## explicitly set columns names for z. Use rownames() for row names. Shocker.
names(z) <- c("names", "Exam 1","Exam 2")
## get dimensions
dim(z)
[1] 6 3
head(z) ## default to first 6 rows
tail(z) ## default to last 6 rows
</code></pre>
<ul>
<li>While very useful, <code>data.frames</code> are more memory intensive than <code>matrices</code></li>
<li>When initializing, if possible, preallocate <code>data.frame</code>, i.e. set size of <code>data.frame</code> before using it</li>
<li>Whenever possible, use <code>matrices</code></li>
</ul>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-30" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Factors</h1>
<p><space></p>
<ul>
<li>Comes from the notion of categorical variables in statistics</li>
<li>Can be thought of as a <code>vector</code> with additional information - categories, or <code>levels</code></li>
<li>Used to split up data sets; commonly seen as columns of <code>data.frame</code>s</li>
</ul>
<pre><code class="r">x <- factor(c("finance", "tech", "tech", "auto", "finance", "energy", "tech"))
print(x)
</code></pre>
<pre><code>[1] finance tech tech auto finance energy tech
Levels: auto energy finance tech
</code></pre>
<pre><code class="r">y <- factor(x, levels = c(levels(x), "tv")) ## include new level, even though no tv data exists
print(y)
</code></pre>
<pre><code>[1] finance tech tech auto finance energy tech
Levels: auto energy finance tech tv
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-31" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Factors</h1>
<p><space></p>
<ul>
<li>use <code>levels</code> to order your levels. Helpful when sorting factors</li>
</ul>
<pre><code class="r">wday <- c("mon", "tues", "mon", "wed", "fri", "wed")
wdayf <- factor(wday)
sort(wdayf) ## did this do what we expected?
</code></pre>
<pre><code>## [1] fri mon mon tues wed wed
## Levels: fri mon tues wed
</code></pre>
<pre><code class="r">wdayf <- factor(wday, levels = c("mon", "tues", "wed", "thurs", "fri")) ## let's add Thursday as well
sort(wdayf)
</code></pre>
<pre><code>## [1] mon mon tues wed wed fri
## Levels: mon tues wed thurs fri
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-32" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Factors</h1>
<p><space></p>
<ul>
<li>Common <code>factor</code> functions</li>
</ul>
<pre><code class="r">z$names2 <- NULL ## NULL removes the object from the factor (or list)
z$gender <- c("m","f","m","f","m","f")
z$party <- c("D","D","R","R","D","D")
</code></pre>
<pre><code class="r">tbl <- table(z$gender,z$party) ## contingency table. class "table"
addmargins(tbl) ## marginal sums
## D R Sum
## f 2 1 3
## m 2 1 3
# # Sum 4 2 6
</code></pre>
</article>
<!-- Presenter Notes -->
</slide>
<slide class="" id="slide-33" style="background:;">
<hgroup>
<h2>Data structures</h2>
</hgroup>
<article>
<h1>Factors</h1>