-
Notifications
You must be signed in to change notification settings - Fork 9
/
presentation.Rmd
1052 lines (648 loc) · 15.6 KB
/
presentation.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 for Data Science"
subtitle: "Beginner's workshop"
author: "AbdulMajedRaja RS"
output:
xaringan::moon_reader:
chakra: libs/remark-latest.min.js
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
---
```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
```
# About Me
- Studied at **Government College of Technology, Coimbatore**
- Bengaluru R user group **Organizer**
- R Packages Developer ( `coinmarketcapr`, `itunesr`)
---
class: inverse
# Disclaimer:
- This workshop is **NOT** going to make you a Data Scientist **in a day**.
- The objective is to help you get a flavor of R and how it is used in Data Science
- Thus, get you ready to embark on your own journey to become a Data Scientist who uses R
---
# Content:
This presentation's content is heavily borrowed from the book [**R for Data Science**](https://r4ds.had.co.nz) by **Garrett Grolemund** and **Hadley Wickham**
.center[<img src="images/r4ds_had_cover.png" width="30%">]
---
# About R
- R is a language and environment for statistical computing and graphics. (Ref: [`r-project.org`](https://www.r-project.org/about.html))
- R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand
- R is Free
- R can be extended (easily) via *packages*.
- R is an interpreted language
.right[![image](images/Rlogo.png)]
---
class: inverse, center, middle
# R Interpreter / Console / GUI
## Demo
---
# About RStudio
- RStudio is a **free and open-source IDE** for R, released by the company **RStudio, Inc.**
- RStudio and its team regularly contribute to R community by releasing new packages, such as:
- `tidyverse`
- `shiny`
- `knitr`
.right[<img src="images/RStudio.png" width="40%">]
---
class: inverse, center, middle
# RStudio
## Demo
---
# R Ecosystem
Like `Python`, `R`'s strength lies in its Ecosystem. **Why R?** - R Packages
### Growth
<figure>
<img src='images/number-of-submitted-packages-to-CRAN.png' width="80% />
<font size="2">
<figcaption> Source: <a href ="https://gist.github.com/daroczig/3cf06d6db4be2bbe3368">@daroczig</a>
</figcaption>
</font>
</figure>
---
class: inverse, center, middle
# Basics of R Programming
---
# Hello, World!
The traditional first step - **Hello, World!**:
--
```{r eval=TRUE, tidy=FALSE}
print("Hello, World!") #<<
```
<br/>
###.center[That's one small step for a man, one giant leap for mankind]
###.center[Neil Armstrong]
---
# Arithmetic Operations
```{r}
2 + 3
```
```{r}
50000 * 42222
```
```{r}
2304 / 233
```
```{r}
(33 + 44 ) * 232 / 12
```
---
# Assignment Operators
### .center[`<-` **Arrow (Less-than < and Minus - )**]
### .center[`=` **(Equal Sign)**]
```{r}
(x <- 2 + 3)
```
```{r}
(y = x ** 4) #<<
```
```{r}
5 * 9 -> a
a + 3
```
---
# Objects
* The entities R operates on are technically known as `objects`.
Example: Vector of numeric
```{r}
vector_of_numeric <- c(2,4,5)
typeof(vector_of_numeric)
```
---
# Vectors
- Atomic Vectors - Homogeneous Data Type
- logical
- integer
- double
- character
- *complex*
- *raw*
- Lists - (Recursive Vectors) Heterogeneous Data Type
- `NULL` is used to represent absence of a vector
**Vectors + Attributes (Additional Meta Data) = Augmented vectors**
* Factors are built on top of integer vectors.
* Dates and date-times are built on top of numeric vectors.
* Data frames and tibbles are built on top of lists.
---
### Numeric Vector
Each element of the numeric vector should be a number.
```{r}
nummy <- c(2,3,4)
nummy_int <- c(1L,2L,3L)
```
```{r}
typeof(nummy)
typeof(nummy_int)
```
```{r}
is.numeric(nummy)
is.numeric(nummy_int)
is.double(nummy)
is.double(nummy_int)
```
---
### Character Vector
```{r}
types <- c("int","double","character")
types
```
```{r}
typeof(types)
length(types)
```
```{r}
is.numeric(types)
is.character(types)
```
---
### Logical Vector
```{r}
logicals <- c(TRUE,F,TRUE,T, FALSE)
logicals
```
---
# Coersion
## Typecasting - Explicit
```{r}
money_in_chars <- c("20","35","33")
typeof(money_in_chars)
```
```{r}
money_money <- as.numeric(money_in_chars)
money_money
typeof(money_money)
```
---
## Typecasting - Implicit
```{r}
money_money <- as.numeric(money_in_chars)
money_money
typeof(money_money)
```
```{r}
new_money <- c(money_money,"33")
new_money
typeof(new_money)
```
---
#Vector - Accessing
```{r}
month.abb #in-built character vector with Month Abbreviations
month.abb[2]
```
```{r}
month.abb[4:7]
```
```{r}
month.abb[c(2,5,7,10)]
```
---
# Vector Manipulation
## Appending
```{r}
days <- c("Mon","Tue","Wed")
days
```
```{r}
week_end <- c("Sat","Sun")
more_days <- c(days,"Thu","Fri",week_end)
more_days
```
---
# Vector - Arithmetic
```{r}
set.seed(122)
so_many_numbers <- runif(10, min = 10, max = 100)
so_many_numbers
```
```{r}
so_many_numbers * 200
```
---
# Factors
* In R, factors are used to work with categorical variables, variables that have a fixed and known set of possible values.
* Useful with Characters where non-Alphabetical Ordering is required
```{r}
days <- c("Thu","Wed","Sun")
sort(days)
```
```{r}
week_levels <- c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
(days_f <- factor(days, levels = week_levels))
```
```{r}
sort(days_f)
```
---
# List
Lists are a step up in complexity from atomic vectors: each element can be any type, not just vectors.
```{r}
(a_list <- list("abcd",123,1:12,month.abb))
```
---
# List Accessing
```{r}
a_list[[1]]
a_list[[4]][4]
```
---
# Matrix
```{r}
new_m <- matrix(data = 1:12, nrow = 3)
new_m
```
```{r}
new_m * 20
```
```{r}
dim(new_m)
new_m[2,3]
```
---
# Dataframe
## Tabular Structure
* dimension
* row.names
* col.names
```{r}
colleges <- c("CIT","GCT","PSG")
year <- c(2019,2018,2017)
db <- data.frame(college_names = colleges, year_since = year)
db
```
---
# Dataframe Manipulation
```{r}
db$college_names
```
```{r}
db[2,2] <- 1990
db
```
```{r}
db[,"year_since"]
```
---
# Loops & Iterators
## For Loop
```{r}
for (month_name in month.abb[1:4]) {
print(paste("This month", month_name, "beautiful!!!"))
}
```
As you move forward, Check the family of `apply` functions - `sapply()`, `tapply()`, `lapply()`, `apply()`.
For advanced functional programming, refer `purrr` package
---
# Logical Operations
## %in% operator
```{r}
iris$Species %in% "virginica"
```
---
## Logical Operators
```{r}
1:10 > 5
```
```{r}
1:10 == 4
```
```{r}
!1:10 == 4
```
---
# Conditions
```{r}
if (iris$Sepal.Length[2]>5) {
print("it is gt 5")
} else print("it is not")
```
```{r}
if (iris$Sepal.Length>10) {print("hello")}
```
```{r}
ifelse(iris$Sepal.Length>6, "more_than_10","les_than_10")
```
---
# Functions
## Types
- Base-R functions (`mean()`, `plot()`, `lm()`)
- Package functions (`dplyr::mutate()`, `stringr::str_detect()`)
- User-defined functions
```{r}
workshop_hate_message <- function(name = "No one", n = 3) {
text_to_print <- paste(name, "hate(s)", "this workshop")
for(i in 1:n) {
print(text_to_print)
}
}
workshop_hate_message("All of us",4)
```
---
# Packages
## Package Installation & Loading
### From CRAN (usually Stable Version)
```{r eval=FALSE}
install.packages("itunesr")
```
**From Github (usually Development Version)**
```{r eval=FALSE}
#install.packages("devtools")
devtools::install_github("amrrs/itunesr")
```
### Loading
```{r eval=FALSE}
library(itunesr)
```
---
# Help
## using `help()`
```{r eval=FALSE}
help("runif")
```
## using ?
```{r eval=FALSE}
?sample
```
---
# Help - Example
```{r}
example("for")
```
---
# Packages Vignette
```{r eval=FALSE}
vignette("dplyr")
browseVignettes("dplyr")
```
---
class: inverse, center, middle
# Data wrangling and Visualization using Tidyverse
---
class: center, middle
# Data Science Framework
There are now like, you know, a billion venn diagrams showing you what data science is. But to me I think the definition is pretty simple. Whenever you're struggling with data, trying to understand what's going on with data, whenever you're trying to turn that **raw data into insight and understanding and discoveries**. I think that's **Data Science.**" - Hadley Wickham
<figure>
<img src='images/hadley_data_science.png' width="80% />
<font size="2">
<figcaption> Source: <a href ="https://www.youtube.com/watch?v=cpbtcsGE0OA">Hadley Wickham</a>
</figcaption>
</font>
</figure>
---
# Tidyverse
- An opinionated collection of R packages designed for data science.
- All packages share an underlying design *philosophy, grammar, and data structures*.
```{r eval=FALSE}
install.packages("tidyverse")
```
### tidyverse packages
```{r}
tidyverse::tidyverse_packages()
```
---
# Loading the Library
```{r}
library(tidyverse)
```
---
# Input Data
Reading the dataset
```{r warning=FALSE, message=FALSE}
#kaggle <- read_csv("data/kaggle_survey_2018.csv")
kaggle <- read_csv("data/kaggle_survey_2018.csv", skip = 1)
```
---
# Basic Stats
### Dimension (Rows Column)
```{r}
dim(kaggle)
```
```{r}
glimpse(kaggle)
```
---
class: inverse, center
# Dataset Overview
## Demo on RStudio
---
# Data Questions (Business Problem)
- What's the percentage of Male and Female respondents?
- What are the top 5 countries?
---
# dyplr verbs
- `mutate()` - adds new variables that are functions of existing variables
- `select()` - picks variables based on their names.
- `filter()` - picks cases based on their values.
- `summarise()` - reduces multiple values down to a single summary.
- `arrange()` - changes the ordering of the rows.
---
# Introducing %>% Pipe Operator
- The pipe, `%>%`, comes from the magrittr package by Stefan Milton Bache
- **Output of LHS** is given as the **input (first argument) of RHS**
### Example
```{r}
kaggle %>% dim()
```
Although doesn't make much sense to use `%>%` in this context, Hope it explains the function.
---
# Percentage of Male and Female
* Column name - `What is your gender? - Selected Choice`
### Pseudo-code
- `group_by` the `kaggle` dataframe on column `What is your gender? - Selected Choice`
- `count` the values
- calculate `percentage` value from the `count`s
---
# % of Male and Female - Group By & Count - Method 1
```{r}
kaggle %>%
group_by(`What is your gender? - Selected Choice`) %>%
summarise(n = n())
```
---
# % of Male and Female - Group By & Count - Method 2
```{r}
kaggle %>%
group_by(`What is your gender? - Selected Choice`) %>%
count()
```
---
# % of Male and Female - Group By & Count - Sorted
```{r}
kaggle %>%
group_by(`What is your gender? - Selected Choice`) %>%
count() %>%
arrange(desc(n))
```
---
# % of Male and Female - Percentage
```{r}
kaggle %>%
group_by(`What is your gender? - Selected Choice`) %>%
count() %>%
ungroup() %>%
mutate(perc = round(n / sum(n),2))
```
---
# % of Male and Female - Nice_Looking_Table
```{r}
kaggle %>%
group_by(`What is your gender? - Selected Choice`) %>%
count() %>%
ungroup() %>%
mutate(perc = round(n / sum(n),2)) %>%
knitr::kable(format = "html")
```
---
class: inverse,center,middle
# But, Wait!!!
## Go Back and See
### If you have only `Male` and `Female`?
---
class: inverse,center,middle
# Time for some cleaning
## In the form of `filter()`ing
---
# % of Male and Female - Filtered_Nice
```{r}
kaggle %>%
filter(`What is your gender? - Selected Choice` %in% c("Male","Female")) %>%
group_by(`What is your gender? - Selected Choice`) %>%
count() %>%
ungroup() %>%
mutate(perc = round(n / sum(n),2)) %>%
knitr::kable(format = "html")
```
---
class: inverse,center,middle
# An Awkward column name, isn't it??!
---
# % of Male and Female - All_Nice_Table
```{r}
library(scales) #for Percentage Formatting
kaggle %>%
filter(`What is your gender? - Selected Choice` %in% c("Male","Female")) %>%
group_by(`What is your gender? - Selected Choice`) %>%
count() %>%
ungroup() %>%
mutate(perc = round(n / sum(n),2)) %>%
mutate(perc = scales::percent(perc)) %>%
rename(Gender = `What is your gender? - Selected Choice`,
Count = n,
Percentage = perc) %>%
knitr::kable(format = "html")
```
---
# Top 5 Countries
* Column name - `In which country do you currently reside?`
### Pseudo-code
- `count` number of respondents from each country
- `arrange` countries in descending order based on their count value
- `top 5` in the list is the output
---
# Top 5 Countries - Code
```{r}
kaggle %>%
count(`In which country do you currently reside?`) %>%
arrange(desc(n)) %>%
top_n(5) %>%
knitr::kable(format = "html")
```
---
class: inverse,center,middle
# Is `Other` a country name???
---
# Top 5 Countries
```{r}
kaggle %>%
filter(!`In which country do you currently reside?` %in% "Other") %>%
count(`In which country do you currently reside?`) %>%
rename(Country = `In which country do you currently reside?`) %>%
arrange(desc(n)) %>%
top_n(5) %>%
knitr::kable(format = "html")
```
---
class: inverse,center,middle
# Table is nice, but a visually appealing plot is Nicer
## 😉
---
# Top 5 Countries - Plot #1
```{r countries1, eval = FALSE}
kaggle %>%
filter(!`In which country do you currently reside?` %in% "Other") %>%
count(`In which country do you currently reside?`) %>%
rename(Country = `In which country do you currently reside?`) %>%
arrange(desc(n)) %>%
top_n(5) %>%
ggplot() + geom_bar(aes(Country,n), stat = "identity") +
coord_flip() +
theme_minimal() +
labs(title = "Top 5 Countries",
subtitle = "From where Kaggle Survey Respondentns reside",
x = "Country",
y = "Number of Respondents",
caption = "Data Source: Kaggle Survey 2018")
```
---
# Top 5 Countries - Plot #2
```{r countries2, echo=FALSE, message=FALSE, warning=FALSE}
kaggle %>%
filter(!`In which country do you currently reside?` %in% "Other") %>%
count(`In which country do you currently reside?`) %>%
rename(Country = `In which country do you currently reside?`) %>%
arrange(desc(n)) %>%
top_n(5) %>%
ggplot() + geom_bar(aes(Country,n), stat = "identity") +
coord_flip() +
theme_minimal() +
labs(title = "Top 5 Countries",
subtitle = "From where Kaggle Survey Respondents reside",
x = "Country",
y = "Number of Respondents",
caption = "Data Source: Kaggle Survey 2018")
```
---
# Top 5 Countries - Plot #3 Themed
```{r countries3, echo=FALSE, message=FALSE, warning=FALSE, fig.width= 10}
library(ggthemes)
kaggle %>%
filter(!`In which country do you currently reside?` %in% "Other") %>%
count(`In which country do you currently reside?`) %>%
rename(Country = `In which country do you currently reside?`) %>%
arrange(desc(n)) %>%
top_n(5) %>%
ggplot() + geom_bar(aes(Country,n), stat = "identity") +
# coord_flip() +