-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.Rmd
2003 lines (1304 loc) · 48.8 KB
/
index.Rmd
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
---
title : Intro to R Workshop
subtitle : UCI Data Science Initiative
author : Sepehr Akhavan, Homer Strong, Fulya Ozcan, Bonnie Bui
job : Dept. of Statistics
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : mathjax # {mathjax, quiz, bootstrap}
logo : logo.png
mode : selfcontained # {standalone, draft}
knit : slidify::knit2slides
github:
user: UCIDataScienceInitiative
repo: IntroR_Workshop
---
## Introduction
1) The class will include 5 sessions:
+ Session 1 (9-10:20): Data Types in R
+ Session 2 (10:30-11:20): Control Structures and Functions
+ Session 3 (11:30-12): Statistical Distributions in R
+ Exercise 1 (12:30-1:20): Basic Data Exploration
+ Session 4 (1:20-2:50): Statistical Analysis in R
+ Session 5 (3:00-4:20): Plotting and Data Visualization in R
+ Exercise 2 (4:20-5:00): Data visualization & Statistical Analysis
---
```{r,echo=FALSE, warning=FALSE, error=FALSE, message=FALSE}
library(ggplot2)
```
## Introduction
2) We are going to work in pairs. Please find a partner.
3) Feel free to ask questions anytime during lectures.
4) To access this presentation and the codes used during the workshop please visit:
+ http://ucidatascienceinitiative.github.io/IntroR_Workshop/#1
---
## Session 1 - Agenda
1. RStudio
2. Data Types in R
3. Subsetting in R
---
## What is R?
+ R is a free software environment for statistical computing and graphics
+ See http://www.r-project.org/ for more info
+ R compiles and runs on a wide variety of UNIX platforms, Windows and Mac OS
+ R is Open-Source and free
+ R is fundamentally a command-driven system
+ R is an object-oriented programming language
+ everything in R is considered as an object!
---
## R Studio:
1. RStudio is a free and open source integrated development environment (IDE) for R.
2. To download RStudio please visit: http://rstudio.org/
3. Please note that you must have R already installed before installing R Studio.
---
## Data Types in R:
1. R has 5 main atomic data types:
+ Numeric
+ Integer
+ Complex
+ Logical
+ Character
2. Everything in R is object. Objects can have some attributes.
+ names, dimension, length are some possible attributes
---
## Vectors in R:
Vector is the most basic object in R
```{r echo=TRUE}
numVec <- 1:10 # <- : is assigning operator
numVec
charVec <- c("a", "b", "c") # c: to combine elements
charVec
logVec <- vector(mode = "logical", length = 10)
logVec
```
---
### Special Values:
There are some special values in R:
+ use L to refer to an integer value: 1L
+ R knows infinity: Inf, -Inf
+ NaN: refers to "Not a number"
```{r echo=TRUE}
intVec <- c(1L, 2L, 3L, 4L)
intVec
a <- Inf; b <- 0
rslt <- c(b/a, a/a)
rslt
```
---
### Logical, Complex, & Character Vectors:
Let's see some examples of logical, complex, and character vectors:
```{r echo=TRUE}
logVec <- c(TRUE, FALSE, FALSE, T, F)
logVec
compVec <- c(1 + 0i, 3 + 1i)
compVec
charVec <- c("red", "green", "blue")
charVec
```
---
### Data Type Coercion:
+ In general, vectors CAN NOT have mixed types of objects
+ exception: lists in R
```{r echo=TRUE, results='hide'}
numCharVec <- c(3.14, "a")
numCharVec # ? what would you expect to be printed?
numLogVec <- c(pi, T)
numLogVec # any guess?
charLogVec <- c("a", TRUE)
charLogVec # ?
```
+ In examples above, we saw implicit coercion
+ Explicit coercion is also possible!
---
### Data Type Coercion:
+ as(): To explicitly coerce objects from one type to another
```{r echo=TRUE}
numVec <- seq(from = 1200, to = 1300, by = 15)
numVec
numToChar <- as(numVec, "character")
numToChar
logVec <- c(F, T, F, T, T)
as(logVec, "numeric")
```
---
### Data Type Coercion:
+ Coercion does not always work! Be careful about warnings:
```{r echo=TRUE}
compVec <- c(12+10i, 1+6i, -3-2i)
as(compVec, "numeric")
charVec <- c("2.5", "3", "2.8", "1.5", "zero")
as(charVec, "numeric")
```
---
### Factors:
+ Factor is a vector object used to specify a discrete classification (categorical values).
+ Factors can be: 1) ordered, 2) un-ordered
+ Levels of a Factor are better to be labeled (self-descriptive)
+ Consider gender as (0, 1) as opposed to labeled ("F", "M")
```{r echo=TRUE}
Gender <- rep(c("Female", "Male"), times = 3)
Gender
GenderFac1 <- factor(Gender)
GenderFac1
```
---
### Factors:
```{r echo=TRUE}
levels(GenderFac1)
table(GenderFac1)
unclass(GenderFac1) # bring the factor down to integer values
```
---
### Factors:
```{r echo=TRUE}
GenderFac1 # levels are ordered alphabetically - 1st level = BaseLevel
GenderFac2 <- factor(Gender, levels = c("Male", "Female"))
GenderFac1
GenderFac2
```
---
### Missing Values:
+ There are two kinds of missing values in R:
+ NaN: refers to "Not a Number" and is a a missing value produced by numerical computation.
+ NA: When a value is "Not Available" or is "Missing", NA is assigned as its value.
+ NaN is also considered as NA (the reverse is NOT true).
```{r echo=TRUE}
testScore <- NA
is.na(testScore)
is.nan(testScore)
```
---
### Matrices:
+ Matrix is a special case of vector:
+ Matrix has dimension attribute
```{r echo=TRUE}
myMat <- matrix(nrow = 2, ncol = 4)
myMat
attributes(myMat)
```
---
### Matrices:
```{r echo=TRUE}
myMat <- matrix(1:8, nrow = 2, ncol = 4)
myMat # matrices are filled in column-wise
```
---
### Matrix is a special vector:
```{r echo=TRUE}
myVec <- 1:8
myVec
dim(myVec) <- c(2,4)
myVec
```
+ Similar to vectors, all elements of a matrix should have the same type.
+ if not, R does an automatic coercion.
---
### Other Ways to Create Matrix:
+ As it's intuitive, matrices seem to be a combination of vectors that are put next to each other (either column wise or row wise).
+ rbind() (row bind) and cbind (column bind) do a similar job:
```{r echo=TRUE}
vec1 <- 1:4
vec2 <- sample(1:100, 4, replace = FALSE)
vec3 <- rnorm(4, mean = 0, sd = 1)
colMat <- cbind(vec1, vec2, vec3)
colMat
```
---
### Other Ways to Create Matrix:
```{r echo=TRUE}
vec1 <- 1:4
vec2 <- sample(1:100, 4, replace = FALSE)
vec3 <- rnorm(4, mean = 0, sd = 1)
rowMat <- rbind(vec1, vec2, vec3)
rowMat
```
---
## Lists:
+ Consider list as a vector but with two main differences:
+ each element of a list can have its own class regardless of other elements
+ This means, each element can be of a different data type and a different length
```{r echo=TRUE}
myVec <- c(10, "R", 10-5i, T)
myList <- list(10, "R", 10-5i, T)
myVec
```
---
## Lists:
```{r echo=TRUE}
myList <- list(10, "R", 10-5i, T)
myList
```
+ Elements of list are shown with [[]]
+ Elements of vector are shown with []
---
## Data Frames:
+ We use data frames to store tabular data
+ Data frame is a special list where all objects have equal length
+ The main difference between data.frame and Matrix?
```{r echo=TRUE}
studentID <- paste("S#", sample(c(6473:7392), 10), sep = "")
score <- sample(c(0:100), 10)
gender <- sample(c("female", "male"), 10, replace = TRUE)
data <- data.frame(studentID = studentID, score = score, gender = gender)
head(data)
```
---
## Subsetting:
+ Often times we need to take a subset of a vector, a matrix, a list, or a dataframe.
+ We consider three main operators to take a subset of an object:
+ [ ]: single brackets return an object of the same class of the original object. By using [], we can also choose more than one element.
+ [[ ]]: double brackets are used primarily for lists and dataframes.
+ "$": is used primarily for lists and dataframes (similar to double brackets).
+ With [[ ]] and $, we can only choose one object!
+ [[ ]] and $ can return an object with a different class than the original objects we are subsetting from.
---
### Subsetting examples:
```{r echo=TRUE}
myVec <- 10:20
myVec[3]
myList <- list(obj1 = "a", obj2 = 10, obj3 = T, obj4 = 10-5i)
myList[[3]]
myList$obj3
```
---
## Subsetting with [ ]:
+ By using single bracket, we can choose more than one element of an object.
+ In this case, index vectors can be very useful:
+ Index vector is a vector of indices of another vector that is used to select a subset of another vector (or Matrix)
```{r echo=TRUE}
x <- seq(from=0, to=100,by=10) # length(x) is ??
IndVec <- c(1, 2, 3, 4, 5) # the first 5 elements
x[IndVec]
```
---
## Index Vectors:
+ There are four types of Index vectors:
1. Logical Index Vector: The logical index vector should be of the same length of the vector from which we are selecting a subset. Values corresponding to TRUE in the index vector are selected.
2. Vector of Positive integers: All the values in this type of index vector must lie in 1:(length(x)).
3. Vector of Negative integers: This type of index vector indicates the values to be excluded from the
vector.
4. A Vector of Character Strings: if a vector has a name attribute, we can simply take a subset of the vector by calling the names of the elements.
---
## Index Vectors:
```{r echo=TRUE}
myVec <- letters[1:10]
names(myVec) <- paste("e", 1:10, sep = "")
myVec
logIndVec <- rep(c(T, F), each = 5)
logIndVec
posIndVec <- 1:5
negIndVec <- -6:-10
chIndVec <- c("e1", "e2", "e3", "e4", "e5")
```
---
## Index Vectors:
```{r echo=TRUE}
myVec[logIndVec]
myVec[negIndVec]
myVec[chIndVec]
```
---
## Logical Index Vectors:
+ logical index vectors can be generated by using conditional statements:
+ Using ==, !=, <, >, ...
```{r echo=TRUE}
myVec <- 1:10
logIndVec <- (myVec < 5)
logIndVec
myVec[logIndVec]
```
---
## Matrix Indexing:
+ Similar to vector indexing, we can refer to individual elements of a matrix.
```{r echo=TRUE}
myMat <- matrix(1:8, ncol = 4)
myMat
myMat[1,1] # refering to an element
myMat[2,] # refering to the second row
myMat[,3] # refering to the third column
```
---
## Matrix Indexing:
+ By default, when the retrieved elements of a matrix look like a vector, R drops their dimension attribute. We can turn this feature off by setting drop = FALSE
```{r echo=TRUE}
myMat[1,1]
myMat[1,1, drop = FALSE]
myMat[2,, drop = FALSE]
```
---
## Subsetting Lists:
```{r echo=TRUE}
myList <- list(ch = letters[1:2], lg = F, nm = 1:3)
myList
myList[1] # subset is still a list
```
---
## Subsetting Lists:
```{r echo=TRUE}
myList[1:2] # subset is still a list
myList[[1]] # returning the 1st obj with its own class
myList$ch # alternative to [[]]
```
---
## Subsetting Lists:
```{r echo=TRUE}
myList[[1]][2] # returning the 2nd element of the 1st obj
myList$ch[2]
myList[[c(1,2)]]
```
---
## Subsetting Data Frames:
```{r echo=TRUE}
library(datasets)
data(quakes) # ?quakes for more info
str(quakes)
head(quakes$long)
```
---
## Subsetting Data Frames:
```{r echo=TRUE}
quakes[1:10,]
```
---
## Time to Break for 10 Minutes :)
---
## Session 2 - Agenda
1. Vectorized Operations in R
2. Reading and Writing in R
3. Control Structure
4. R Packages and Functions
---
## Vectorized Operations
R is capable of vectorized operations without any need for running loops:
```{r echo=TRUE}
x <- 1:5
y <- c(1, 2, 6, 7, 10)
x + y # R does an element by element summation
x < y
```
---
## Vectorized Operations
+ Similar to vectors, vectorized operations can be performed for Matrices:
```{r echo=TRUE}
x <- matrix(1:9, ncol = 3)
y <- matrix(rep(c(5,6,7), 3), ncol = 3)
x + y # R does an element by element summation
x < y
```
---
## Reading and Writing Data
**The slides for "Reading and Writing Data" section were mainly from Dr. Roger D. Peng, Associate Professor at Johns Hopkins**
Main functions for reading data into R:
1. read.table(), read.csv(): to read tabular data
2. readLines(): to read lines of a text file
3. source(), dget(): reading R codes
4. load(): to read saved workspaces
+ Only read.table() and read.csv() are covered in this lecture.
---
## Reading and Writing Data
Main functions for writing data from R:
1. write.table(), write.csv(): to write tabular data to file
2. writeLines(): to write lines to a text file
3. dump, dput: to write R codes to a file
4. save: to save a workspace
+ Only write.table() is covered in this lecture.
---
## read.table():
+ read.table() is the most commonly used function to read data in R. Below are important arguments of this function:
+ file: name or address to the file of interest
+ header: logical indicator on whether the file has header or not
+ sep: string on how columns of data are separated (in .csv, sep = ",")
+ colClasses: is a character vector for class of each column
+ nrows: number of rows in the dataset
+ comment.char: a character that is used in the dataset for commenting
+ skip: number of lines to skip from the beginning of the file
+ stringAsFactors: logical indicator on whether characters should be converted to factors
+ read.csv() is equivalent to read.table with sep = "," and header = TRUE
---
## read.table():
```{r echo = TRUE, eval=TRUE}
irisFile <- read.table(file = "iris.csv", sep=",", header = TRUE)
head(irisFile)
```
+ to make read.table() run faster:
+ set comment.char = " "
+ set colClasses upfront
---
## Calculating Memory Requirements:
+ Note that datasets will be read into RAM. So, you should have enough RAM in order to read a dataset.
+ Consider a data frame with 1.5 million rows and 120 columns. How much memory is required to read this dataset?
1.5m * 120 * 8 bytes/numeric = 1.44 * $10^9$ = 1.44 * $10^9$/ $2^{20}$ MB = 1,373.29 MB = 1.34 GB
+ So it's recommended to have a RAM of size 2 * 1.34GB to read that dataset.
---
## write.table():
```{r echo = T, eval=FALSE}
write.table(irisFile, file = "path/to/the/file")
```
---
## Loops:
+ There are 3 ways in R to write loops:
+ for
+ repeat (skipped!)
+ while (skipped!)
---
### for:
```{r echo = T}
for(i in 1:4){
print(paste("cycle #", i, sep = ""))
i <- i + 1
}
```
---
## if:
+ if/else statements are used to write conditional statements
```{r echo = T}
x <- 7
if (x < 10){
print("x is less than 10")
}else{
print("x is greater than 10")
}
```
---
## if:
```{r echo = T}
age <- sample(1:100, 10)
ageCat <- rep(NA, length(age))
for (i in 1:(length(age))) {
if (age[i] <= 35){
ageCat[i] <- "Young"
}else if (age[i] <= 55){
ageCat[i] <- "Middle-Aged"
}else{
ageCat[i] <- "Old"
}
}
age.df <- data.frame(age = age, ageCat = ageCat)
age.df[1:3,]
```
---
## Functions and Packages:
1. R language has many built-in functions
2. Each function has a name followed by ()
3. Arguments of a function are put within parentheses
4. R packages are a comfortable way to maintain collections of R functions and data sets
5. Packages allow for easy, transparent and cross-platform extension of the R base system
---
## Functions and Packages:
There are some terms which sometimes get confused and should be clarified:
1. Package: An extension of the R base system with code, data and documentation in a standardized format
2. Library: A directory containing installed packages
3. Repository: A website providing packages for installation
4. Source: The original version of a package with human-readable text and code
5. Base packages: Part of the R source tree, maintained by R Core
+ for more info on how R packages are developed, please read: "Creating R Packages: A Tutorial" (Friedrich Leisch)
+ http://cran.r-project.org/doc/contrib/Leisch-CreatingPackages.pdf
---
## How to install a package in R:
There are three main ways to install a package in R:
1. Installing from CRAN: install a package directly from the repository
+ Using R studio: tools/install packages
+ From R console: install.packages()
2. Installing from Source: In this method, you should first download the add-on R package and use the following unix command in the console to install the package:
+ R CMD INSTALL packageName -l path/to/your/Rpackage/Directory
3. Installing from a version control (Github):
+ Check-out https://github.com/hadley/devtools
+ Once you install a package, you need to load it into R using the function library()
---
## Popular Packages in R:
1. To visualize data:
+ ggplot2: to create beautiful graphics
+ googleVis: to use Google Chart tools
2. To report results:
+ shiny: to create interactive web-based apps
+ knitr: to combine R codes and Latex/Markdown codes
+ slidify: to build HTML 5 slide shows
3. To write high-performance R code:
+ Rcpp: to write R functions that call C++ code
+ data.table: to organize datasets for fast operations
+ parallel: to use parallel processing in R
---
## Calling a function in R
```{r echo=TRUE}
str(sample)
```
+ consider sample() in R. Simply run ?sample in R console to read the help on this function.
+ sample() gets four arguments:
+ x: sample space in form of a vector
+ size: your desired sample size
+ replace: sampling with/without replacement
+ prob: a vector of probability weights
+ some of the arguments have default values. What are those arguments?
+ How to use (or call) this function?
---
## Calling a function in R
```{r echo=TRUE}
# Functions arguments can be matched: 1) by position or 2) by name
sampSpace <- 1:6 # rolling a die
sample(sampSpace, 1) # arguments with default values can be omitted
sample(size = 1, x = sampSpace) # no need to remember the order
sample(size = 1, sampSpace)
```
---
## Writing your Own functions
```{r echo=TRUE, eval=FALSE}
yourFnName <- function(<your arguments>){
# body of your code
# return the output of the function
}
# to use your function, you can simply call the function name as:
yourFnName(<set values for the input arguments>)
```
---
## Writing your Own functions
+ Let's write a function that gets three arguments: a, b, c
+ The function then returns min of these two numbers
```{r echo=TRUE, eval=TRUE}
myMin <- function(a, b, c){
myMinVal <- min(a, b, c)
return(myMinVal)
}
myMin(10, 20, 30)
myMin(10, NA, 20) # ? how to fix this so it returns 10
```
---
## Some notes on Functions
> 1. Variables defined within a function are locally defined (i.e. not defined outside of the function).
> 2. Functions in R are treated like any other first class objects. This means functions can be passed as arguments of other functions.
> 3. Arguments of functions are evaluated as they are needed (lazy evaluation).
> 4. " ... " can be an argument of a function and it refers to a situation where number of input arguments can be varied and is not fixed upfront.
---
## Lazy Evaluation of Function Arguments
```{r echo=TRUE}
myLazyFn1 <- function(a, b){
return(a)
}
myLazyFn1(10) # No error!
myLazyFn2 <- function(a, b){
print(a)
print(b)
return(1)
}
myLazyFn2(10)
```
---
## Some useful functions:
+ Here we are going to talk about:
+ str(): a function to explain internal structure of a function
+ apply(): to apply a function to a matrix or dataframe
+ lapply(), sapply(), tapply(), mapply(): applying a function to a vector
+ split(): to split a dataset by levels of a factor
---
### str():
+ str() is a compact way of understanding what an object is and what is in that object.
```{r echo=TRUE}
str(str)
str(sample)
genderF <- factor(sample(c("Male", "Female"), 20, replace = TRUE))
str(genderF)
```
---
### str():
```{r echo=TRUE}
myMat <- matrix(1:10, ncol = 5)
str(myMat)
myList <- list(numVec = 1:3, logVec = F, charVec = LETTERS[1:4])
str(myList)
```
---
### apply():
```{r echo=TRUE}
str(apply) # try ?apply for more info
```
+ apply() is a useful function to apply a function (FUN) on a MARGIN of a matrix or dataframe (X)
+ MARGIN: a vector giving the subscripts which the function will be applied over
+ 1: indicates rows
+ 2: indicates columns
+ c(1, 2): indicates rows and columns
+ FUN: refers to the function that we want to apply on the dataset
+ "..." : additional arguments of FUN
---
### apply():
```{r echo=TRUE}
myMat <- matrix(1:10, ncol = 5)
myMat[2,c(2, 5)] <- NA
myMat
apply(myMat, 2, sum, na.rm = TRUE)
```
---
### apply():
```{r echo=TRUE}
# consider iris dataset:
head(iris) # more info ?iris
# suppose we are interested in getting 25% and 75% of each numeric column
```
---
### apply():
```{r echo=TRUE}
# Consider iris dataset:
apply(iris[,-5], 2, quantile, probs = c(0.25, 0.75))
```
---
### lapply() and sapply():
```{r echo=TRUE}
str(lapply)
str(sapply)
```
+ x: a list, dataframe, or a vector
+ FUN: the function to be applied to each element of X
+ "...": other arguments of FUN
---
### lapply() and sapply():
```{r echo=TRUE}
myList <- list(e1 = 1:10, e2 = -1:-10)
lapply(myList, mean)
sapply(myList, mean)
```
---
### lapply() v. sapply()?:
+ sapply() simplifies the result of lapply.
+ If the result of lapply is a list with all elements of the same length:
+ if length == 1: sapply() returns a vector
+ if length != 1: sapply() returns a matrix
+ otherwise, sapply() generates a list similar to lapply()
---
### lapply() & sapply() with a user-defined FUN
```{r echo=TRUE}
myList <- list(e1 = 1:10, e2 = -1:-10)
lapply(myList, function(element){return(mean(c(element[1], element[length(element)])))})
sapply(myList, function(element){return(mean(c(element[1], element[length(element)])))})
```
---
### tapply():
```{r echo = TRUE}
str(tapply)
```
+ tapply() applies a function on a subset of a vector
+ X: is a vector
+ INDEX: list of one or more factors, each of same length as X
+ FUN: our function of interest
+ "...": other arguments of FUN
+ simplify: any guess???
---