-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tex
4234 lines (3438 loc) · 160 KB
/
index.tex
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
% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
\PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor}
%
\documentclass[
letterpaper,
DIV=11,
numbers=noendperiod]{scrreprt}
\usepackage{amsmath,amssymb}
\usepackage{lmodern}
\usepackage{iftex}
\ifPDFTeX
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
\usepackage{unicode-math}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
\KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{241,243,245}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.40,0.46,0.14}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\BuiltInTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\ExtensionTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.28,0.35,0.67}{#1}}
\newcommand{\ImportTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\NormalTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.07,0.07,0.07}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{3}
% Make \paragraph and \subparagraph free-standing
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
\newlength{\cslhangindent}
\setlength{\cslhangindent}{1.5em}
\newlength{\csllabelwidth}
\setlength{\csllabelwidth}{3em}
\newlength{\cslentryspacingunit} % times entry-spacing
\setlength{\cslentryspacingunit}{\parskip}
\newenvironment{CSLReferences}[2] % #1 hanging-ident, #2 entry spacing
{% don't indent paragraphs
\setlength{\parindent}{0pt}
% turn on hanging indent if param 1 is 1
\ifodd #1
\let\oldpar\par
\def\par{\hangindent=\cslhangindent\oldpar}
\fi
% set entry spacing
\setlength{\parskip}{#2\cslentryspacingunit}
}%
{}
\usepackage{calc}
\newcommand{\CSLBlock}[1]{#1\hfill\break}
\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{#1}}
\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{#1}\break}
\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
\KOMAoption{captions}{tableheading}
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[many]{tcolorbox}}
\@ifpackageloaded{fontawesome5}{}{\usepackage{fontawesome5}}
\definecolor{quarto-callout-color}{HTML}{909090}
\definecolor{quarto-callout-note-color}{HTML}{0758E5}
\definecolor{quarto-callout-important-color}{HTML}{CC1914}
\definecolor{quarto-callout-warning-color}{HTML}{EB9113}
\definecolor{quarto-callout-tip-color}{HTML}{00A047}
\definecolor{quarto-callout-caution-color}{HTML}{FC5300}
\definecolor{quarto-callout-color-frame}{HTML}{acacac}
\definecolor{quarto-callout-note-color-frame}{HTML}{4582ec}
\definecolor{quarto-callout-important-color-frame}{HTML}{d9534f}
\definecolor{quarto-callout-warning-color-frame}{HTML}{f0ad4e}
\definecolor{quarto-callout-tip-color-frame}{HTML}{02b875}
\definecolor{quarto-callout-caution-color-frame}{HTML}{fd7e14}
\makeatother
\makeatletter
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\AtBeginDocument{%
\renewcommand*\contentsname{Table of contents}
\renewcommand*\listfigurename{List of Figures}
\renewcommand*\listtablename{List of Tables}
\renewcommand*\figurename{Figure}
\renewcommand*\tablename{Table}
}
\@ifpackageloaded{float}{}{\usepackage{float}}
\floatstyle{ruled}
\@ifundefined{c@chapter}{\newfloat{codelisting}{h}{lop}}{\newfloat{codelisting}{h}{lop}[chapter]}
\floatname{codelisting}{Listing}
\newcommand*\listoflistings{\listof{codelisting}{List of Listings}}
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\@ifpackageloaded{subcaption}{}{\usepackage{subcaption}}
\makeatother
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[many]{tcolorbox}}
\makeatother
\makeatletter
\@ifundefined{shadecolor}{\definecolor{shadecolor}{rgb}{.97, .97, .97}}
\makeatother
\makeatletter
\makeatother
\ifLuaTeX
\usepackage{selnolig} % disable illegal ligatures
\fi
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\urlstyle{same} % disable monospaced font for URLs
\hypersetup{
pdftitle={Fitting a Model},
pdfauthor={Andrea Carenzo},
colorlinks=true,
linkcolor={blue},
filecolor={Maroon},
citecolor={Blue},
urlcolor={Blue},
pdfcreator={LaTeX via pandoc}}
\title{Fitting a Model}
\author{Andrea Carenzo}
\date{2022-05-23T00:00:00+02:00}
\begin{document}
\maketitle
\ifdefined\Shaded\renewenvironment{Shaded}{\begin{tcolorbox}[boxrule=0pt, interior hidden, borderline west={3pt}{0pt}{shadecolor}, enhanced, sharp corners, frame hidden]}{\end{tcolorbox}}\fi
\renewcommand*\contentsname{Table of contents}
{
\hypersetup{linkcolor=}
\setcounter{tocdepth}{2}
\tableofcontents
}
\hypertarget{welcome}{%
\chapter*{Welcome}\label{welcome}}
\addcontentsline{toc}{chapter}{Welcome}
I personally consider \href{https://www.r-project.org/}{R} and
\href{https://www.python.org/}{Python} to be two very powerful
programming languages (and ecosystems) to make \emph{data science}.
Being mainly an R user for three years, I had to learn
(\textbf{quickly}) Python and its modules for data science due to a
change of career. Starting to learn a programming language from scratch
and getting familiar with the APIs of lots of packages can be
overwhelming. Hence, I started looking for similarities across the R and
Python ecosystems and I've decided to create this book as a personal
reference to be able to switch from one language to another seamlessly.
This book must not be intended as an in-depth guide into any of the
concepts exposed. Instead, it should be considered as a
\textbf{dictionary} aimed at translating many common data science
problems from R to Python and viceversa. The current version of this
dictionary covers the following macro-areas of data science:
\begin{itemize}
\tightlist
\item
Data Collection
\item
Data Manipulation
\item
Data Visualization
\item
Machine Learning
\end{itemize}
Obviously, data science is a broader topic and you can find links to
external useful resources throughout the book. I chose to translate the
most common and useful commands with code snippets which needed to be
both concise and as accurate as possible.
This project was created with the language-agnostic publishing system
\href{https://quarto.org/}{Quarto}, which can be considered as a younger
(yet very ambitious) brother of
\href{https://rmarkdown.rstudio.com/}{\texttt{rmarkdown}}.
Hopefully, this resource may help someone else in their journey through
data science with R and Python. Enjoy.
\hypertarget{introduction}{%
\chapter{Introduction}\label{introduction}}
Before taking your bilingual journey through data science, I want to
highlight some useful resources which can improve your overall learning
experience.
\hypertarget{choose-an-ide}{%
\section{Choose an IDE}\label{choose-an-ide}}
Making data science in the command line is ok, but you can save time and
improve a lot your workflow by using an integrated development
environment (IDE). You will have the ability to create scripts, running
code interactively, making plots, debugging code and more within a
single application.
In my opinion, the
\href{https://www.rstudio.com/products/rstudio/}{RStudio IDE} is the
best solution out there for R at present.
For Python, good choices are \href{https://www.spyder-ide.org/}{Spyder},
\href{https://www.jetbrains.com/pycharm/}{PyCharm} and
\href{https://jupyter.org/}{Jupyter}.
\hypertarget{learn-by-others-and-improve-yourself}{%
\section{Learn by others and improve
yourself}\label{learn-by-others-and-improve-yourself}}
\hypertarget{kaggle}{%
\subsection{Kaggle}\label{kaggle}}
\href{https://www.kaggle.com/}{Kaggle} is an online platform hosting
datasets and competitions aimed at solving real-life problems. This is
one of the best places to getting your hands dirty in data science!
Throughout the book, we will use many (?) Kaggle datasets. You can
install the CLI of \href{https://www.kaggle.com/docs/api}{Kaggle API}
and run the following command on bash to download a dataset:
\begin{Shaded}
\begin{Highlighting}[]
\ExtensionTok{kaggle}\NormalTok{ datasets download kamilpytlak/personal{-}key{-}indicators{-}of{-}heart{-}disease ./data }\AttributeTok{{-}{-}unzip}
\end{Highlighting}
\end{Shaded}
\hypertarget{tidytuesday}{%
\subsection{TidyTuesday}\label{tidytuesday}}
As described in the main page,
\href{https://github.com/rfordatascience/tidytuesday}{TidyTuesday} is a
weekly social data project aimed at applying your R skills, getting
feedback, exploring other's work and connecting with the greater R
community. Every week (yes, on Tuesday), a new dataset is posted on the
GitHub page and people are encouraged to produce useful insights from it
(usually) through figures. Once you're done with your visualization, you
can post it on Twitter by using the hashtags \textbf{\#TidyTuesday} and
\textbf{\#RStats}. It is also recommended to share your code and adding
alt text to your visualizations.
\hypertarget{big-books}{%
\subsection{Big Books}\label{big-books}}
There will be lots of links to external resources throughout the book.
Anyway, I suggest you to take a look at these two meta-books which can
help you to point to the right direction in your learning path:
\begin{itemize}
\tightlist
\item
\href{https://www.bigbookofr.com/}{the Big Book of R};
\item
\href{https://www.bigbookofpython.com/}{the Big Book of Python}.
\end{itemize}
\hypertarget{integrate-r-and-python}{%
\section{Integrate R and Python}\label{integrate-r-and-python}}
If you want to integrate Python code in your R projects, I suggest you
to take a look at the R package
\href{https://rstudio.github.io/reticulate/}{\texttt{reticulate}}.
For example, it is possible to import Python libraries and use their
functions to create R objects. In the following code chunk, you can see
how we import Numpy and Pandas (using R syntax), create two Numpy arrays
(R vectors) and use them to make a Pandas DataFrame (R data.frame):
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(reticulate)}
\NormalTok{np }\OtherTok{\textless{}{-}} \FunctionTok{import}\NormalTok{(}\StringTok{"numpy"}\NormalTok{)}
\NormalTok{pd }\OtherTok{\textless{}{-}} \FunctionTok{import}\NormalTok{(}\StringTok{"pandas"}\NormalTok{)}
\NormalTok{a1 }\OtherTok{\textless{}{-}}\NormalTok{ np}\SpecialCharTok{$}\FunctionTok{array}\NormalTok{(}\FunctionTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{, }\DecValTok{2}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{4}\NormalTok{))}
\NormalTok{a2 }\OtherTok{\textless{}{-}}\NormalTok{ np}\SpecialCharTok{$}\FunctionTok{array}\NormalTok{(}\DecValTok{5}\SpecialCharTok{:}\DecValTok{8}\NormalTok{)}
\NormalTok{pd}\SpecialCharTok{$}\FunctionTok{DataFrame}\NormalTok{(}\FunctionTok{list}\NormalTok{(}\AttributeTok{a1 =}\NormalTok{ a1, }\AttributeTok{a2 =}\NormalTok{ a2), }\AttributeTok{index =}\NormalTok{ letters[}\DecValTok{1}\SpecialCharTok{:}\DecValTok{4}\NormalTok{])}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
a1 a2
a 1 5
b 2 6
c 3 7
d 4 8
\end{verbatim}
You can also use Python interactively through the R console
(\texttt{reticulate::repl\_python()} function) or sourcing Python
scripts (\texttt{reticulate::source\_python()}) and more.
\part{Data Collection}
Data collection is the most fundamental part of data science. Data can
be imported into R and Python from many sources: csv, txt, pdf and even
from html pages.
The following chapters will show you how to import data into R and
Python from several sources using different packages:
\begin{itemize}
\tightlist
\item
\href{https://readr.tidyverse.org/}{\texttt{readr}} and
\href{https://pandas.pydata.org/}{\texttt{Pandas}} for the most common
tabular data formats;
\item
\href{}{\texttt{readxl}} and \href{}{\texttt{openpyxl}} for Excel
files;
\item
\href{https://CRAN.R-project.org/package=jsonlite}{\texttt{jsonlite}}
and \href{https://docs.python.org/3/library/json.html}{\texttt{json}}
for JSON files;
\item
\href{https://xml2.r-lib.org/}{\texttt{xml2}} and \textbf{???} for XML
files;
\item
\href{}{\texttt{DBI}} and ??? for SQL databases;
\item
\href{https://rvest.tidyverse.org/}{\texttt{rvest}} and
\href{https://www.crummy.com/software/BeautifulSoup/bs4/doc/}{\texttt{Beautiful\ Soup}}
for web scraping;
\item
\href{https://httr2.r-lib.org/}{\texttt{httr2}} and
\href{https://docs.python-requests.org/en/master/}{\texttt{Requests}}
to interrogate APIs.
\end{itemize}
\hypertarget{structured-data}{%
\chapter{Structured Data}\label{structured-data}}
The most common tabular (or structured) file formats one may encounter
in a data science project are:
\begin{itemize}
\tightlist
\item
delimited files such as \textbf{CSV} (comma-separated values) and
\textbf{TSV} (tab-separated values) files;
\item
\textbf{Excel} files.
\end{itemize}
We will consider the
\href{https://www.kaggle.com/kamilpytlak/personal-key-indicators-of-heart-disease}{Personal
key indicators of heart disease} from Kaggle.
\begin{Shaded}
\begin{Highlighting}[]
\ExtensionTok{kaggle}\NormalTok{ datasets download kamilpytlak/personal{-}key{-}indicators{-}of{-}heart{-}disease ./data }\AttributeTok{{-}{-}unzip}
\end{Highlighting}
\end{Shaded}
\hypertarget{r}{%
\subsubsection{R}\label{r}}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(readr)}
\end{Highlighting}
\end{Shaded}
\hypertarget{python}{%
\subsubsection{Python}\label{python}}
\begin{Shaded}
\begin{Highlighting}[]
\ImportTok{import}\NormalTok{ pandas }\ImportTok{as}\NormalTok{ pd}
\end{Highlighting}
\end{Shaded}
\hypertarget{delimited-files}{%
\section{Delimited files}\label{delimited-files}}
\hypertarget{tsv}{%
\subsection{TSV}\label{tsv}}
As an example, let's consider the
\href{https://github.com/rfordatascience/tidytuesday/blob/master/data/2020/2020-05-05}{Animal
Crossing} dataset from week 19 of the 2020 TidyTuesday challenge.
\hypertarget{r-1}{%
\subsubsection{R}\label{r-1}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{url }\OtherTok{\textless{}{-}} \StringTok{"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020{-}05{-}05/critic.tsv"}
\NormalTok{df }\OtherTok{\textless{}{-}} \FunctionTok{read\_tsv}\NormalTok{(url, }\AttributeTok{show\_col\_types =} \ConstantTok{FALSE}\NormalTok{)}
\NormalTok{df}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 107 x 4
grade publication text date
<dbl> <chr> <chr> <date>
1 100 Pocket Gamer UK Animal Crossing; New Horizons, much like i~ 2020-03-16
2 100 Forbes Know that if you’re overwhelmed with the w~ 2020-03-16
3 100 Telegraph With a game this broad and lengthy, there’~ 2020-03-16
4 100 VG247 Animal Crossing: New Horizons is everythin~ 2020-03-16
5 100 Nintendo Insider Above all else, Animal Crossing: New Horiz~ 2020-03-16
6 100 Trusted Reviews Animal Crossing: New Horizons is the best ~ 2020-03-16
7 100 VGC Nintendo's comforting life sim is a tranqu~ 2020-03-16
8 100 God is a Geek A beautiful, welcoming game that is everyt~ 2020-03-16
9 100 Nintendo Life Animal Crossing: New Horizons takes Animal~ 2020-03-16
10 100 Daily Star Similar to how Breath of the Wild and Odys~ 2020-03-16
# ... with 97 more rows
\end{verbatim}
\hypertarget{python-1}{%
\subsubsection{Python}\label{python-1}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{url }\OperatorTok{=} \StringTok{"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020{-}05{-}05/critic.tsv"}
\NormalTok{df }\OperatorTok{=}\NormalTok{ pd.read\_table(url)}
\NormalTok{df}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
grade ... date
0 100 ... 2020-03-16
1 100 ... 2020-03-16
2 100 ... 2020-03-16
3 100 ... 2020-03-16
4 100 ... 2020-03-16
.. ... ... ...
102 90 ... 2020-04-16
103 90 ... 2020-04-17
104 95 ... 2020-04-22
105 90 ... 2020-05-01
106 80 ... 2020-05-01
[107 rows x 4 columns]
\end{verbatim}
\hypertarget{csv}{%
\subsection{CSV}\label{csv}}
As an example, let's consider the
\href{https://github.com/rfordatascience/tidytuesday/blob/master/data/2022/2022-04-12}{Indoor
Pollution} dataset from week 15 of the 2022 TidyTuesday challenge.
\hypertarget{r-2}{%
\subsubsection{R}\label{r-2}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{url }\OtherTok{\textless{}{-}} \StringTok{"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022{-}04{-}12/indoor\_pollution.csv"}
\FunctionTok{read\_csv}\NormalTok{(url, }\AttributeTok{show\_col\_types =} \ConstantTok{FALSE}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 8,010 x 4
Entity Code Year `Deaths - Cause: All causes - Risk: Household air p~`
<chr> <chr> <dbl> <dbl>
1 Afghanistan AFG 1990 19.6
2 Afghanistan AFG 1991 19.3
3 Afghanistan AFG 1992 19.5
4 Afghanistan AFG 1993 19.7
5 Afghanistan AFG 1994 19.4
6 Afghanistan AFG 1995 19.6
7 Afghanistan AFG 1996 19.8
8 Afghanistan AFG 1997 19.7
9 Afghanistan AFG 1998 19.0
10 Afghanistan AFG 1999 19.9
# ... with 8,000 more rows
\end{verbatim}
\hypertarget{python-2}{%
\subsubsection{Python}\label{python-2}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{url }\OperatorTok{=} \StringTok{"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022{-}04{-}12/indoor\_pollution.csv"}
\NormalTok{pd.read\_csv(url)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
Entity ... Deaths - Cause: All causes - Risk: Household air pollution from solid fuels - Sex: Both - Age: Age-standardized (Percent)
0 Afghanistan ... 19.623001
1 Afghanistan ... 19.335193
2 Afghanistan ... 19.508785
3 Afghanistan ... 19.677607
4 Afghanistan ... 19.432528
... ... ... ...
8005 Zimbabwe ... 8.603630
8006 Zimbabwe ... 8.656817
8007 Zimbabwe ... 8.690100
8008 Zimbabwe ... 8.736245
8009 Zimbabwe ... 8.658818
[8010 rows x 4 columns]
\end{verbatim}
\hypertarget{general-delimiter}{%
\subsection{General delimiter}\label{general-delimiter}}
Again, we can consider the
\href{https://github.com/rfordatascience/tidytuesday/blob/master/data/2020/2020-05-05}{Animal
Crossing} dataset from TidyTuesday and use the \texttt{read\_table}
function to import the data by specifying a separator/delimiter.
\hypertarget{r-3}{%
\subsubsection{R}\label{r-3}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{url }\OtherTok{\textless{}{-}} \StringTok{"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020{-}05{-}05/critic.tsv"}
\FunctionTok{read\_delim}\NormalTok{(url, }\AttributeTok{delim =}\StringTok{"}\SpecialCharTok{\textbackslash{}t}\StringTok{"}\NormalTok{, }\AttributeTok{show\_col\_types =} \ConstantTok{FALSE}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 107 x 4
grade publication text date
<dbl> <chr> <chr> <date>
1 100 Pocket Gamer UK Animal Crossing; New Horizons, much like i~ 2020-03-16
2 100 Forbes Know that if you’re overwhelmed with the w~ 2020-03-16
3 100 Telegraph With a game this broad and lengthy, there’~ 2020-03-16
4 100 VG247 Animal Crossing: New Horizons is everythin~ 2020-03-16
5 100 Nintendo Insider Above all else, Animal Crossing: New Horiz~ 2020-03-16
6 100 Trusted Reviews Animal Crossing: New Horizons is the best ~ 2020-03-16
7 100 VGC Nintendo's comforting life sim is a tranqu~ 2020-03-16
8 100 God is a Geek A beautiful, welcoming game that is everyt~ 2020-03-16
9 100 Nintendo Life Animal Crossing: New Horizons takes Animal~ 2020-03-16
10 100 Daily Star Similar to how Breath of the Wild and Odys~ 2020-03-16
# ... with 97 more rows
\end{verbatim}
\hypertarget{python-3}{%
\subsubsection{Python}\label{python-3}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{url }\OperatorTok{=} \StringTok{"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020{-}05{-}05/critic.tsv"}
\NormalTok{pd.read\_table(url, sep}\OperatorTok{=}\StringTok{"}\CharTok{\textbackslash{}t}\StringTok{"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
grade ... date
0 100 ... 2020-03-16
1 100 ... 2020-03-16
2 100 ... 2020-03-16
3 100 ... 2020-03-16
4 100 ... 2020-03-16
.. ... ... ...
102 90 ... 2020-04-16
103 90 ... 2020-04-17
104 95 ... 2020-04-22
105 90 ... 2020-05-01
106 80 ... 2020-05-01
[107 rows x 4 columns]
\end{verbatim}
\hypertarget{excel-files}{%
\section{Excel files}\label{excel-files}}
At the moment, \texttt{readxl} does not support reading files from URLs.
Hence, we will consider an example dataset which comes into the
\texttt{readxl} package.
\hypertarget{r-4}{%
\subsubsection{R}\label{r-4}}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(readxl)}
\NormalTok{path\_to\_ds }\OtherTok{\textless{}{-}} \FunctionTok{readxl\_example}\NormalTok{(}\StringTok{"clippy.xlsx"}\NormalTok{)}
\FunctionTok{read\_xlsx}\NormalTok{(path\_to\_ds)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
# A tibble: 4 x 2
name value
<chr> <chr>
1 Name Clippy
2 Species paperclip
3 Approx date of death 39083
4 Weight in grams 0.9
\end{verbatim}
\hypertarget{python-4}{%
\subsubsection{Python}\label{python-4}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{pd.read\_excel(r.path\_to\_ds)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
name value
0 Name Clippy
1 Species paperclip
2 Approx date of death 2007-01-01 00:00:00
3 Weight in grams 0.9
\end{verbatim}
\hypertarget{summarize-your-data}{%
\section{Summarize your data}\label{summarize-your-data}}
\begin{tcolorbox}[standard jigsaw,bottomtitle=1mm, opacitybacktitle=0.6, coltitle=black, colback=white, arc=.35mm, leftrule=.75mm, titlerule=0mm, rightrule=.15mm, opacityback=0, colframe=quarto-callout-tip-color-frame, title=\textcolor{quarto-callout-tip-color}{\faLightbulb}\hspace{0.5em}{The skimr package}, toprule=.15mm, colbacktitle=quarto-callout-tip-color!10!white, bottomrule=.15mm, toptitle=1mm, left=2mm]
The \href{https://docs.ropensci.org/skimr/}{\texttt{skimr}} package can
be very useful to easily summarize your data!
\end{tcolorbox}
\hypertarget{r-5}{%
\subsubsection{R}\label{r-5}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{skimr}\SpecialCharTok{::}\FunctionTok{skim}\NormalTok{(df)}
\end{Highlighting}
\end{Shaded}
\begin{longtable}[]{@{}ll@{}}
\caption{Data summary}\tabularnewline
\toprule()
\endhead
Name & df \\
Number of rows & 107 \\
Number of columns & 4 \\
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ & \\
Column type frequency: & \\
character & 2 \\
Date & 1 \\
numeric & 1 \\
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ & \\
Group variables & None \\
\bottomrule()
\end{longtable}
\textbf{Variable type: character}
\begin{longtable}[]{@{}
>{\raggedright\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.1944}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.1389}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.1944}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.0556}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.0556}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.0833}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.1250}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 14\tabcolsep) * \real{0.1528}}@{}}
\toprule()
\begin{minipage}[b]{\linewidth}\raggedright
skim\_variable
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
n\_missing
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
complete\_rate
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
min
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
max
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
empty
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
n\_unique
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
whitespace
\end{minipage} \\
\midrule()
\endhead
publication & 0 & 1 & 2 & 29 & 0 & 107 & 0 \\
text & 0 & 1 & 22 & 833 & 0 & 107 & 0 \\
\bottomrule()
\end{longtable}
\textbf{Variable type: Date}
\begin{longtable}[]{@{}
>{\raggedright\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1750}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1250}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1750}}
>{\raggedright\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1375}}
>{\raggedright\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1375}}
>{\raggedright\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1375}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 12\tabcolsep) * \real{0.1125}}@{}}
\toprule()
\begin{minipage}[b]{\linewidth}\raggedright
skim\_variable
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
n\_missing
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
complete\_rate
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
min
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
max
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
median
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
n\_unique
\end{minipage} \\
\midrule()
\endhead
date & 0 & 1 & 2020-03-16 & 2020-05-01 & 2020-03-23 & 28 \\
\bottomrule()
\end{longtable}
\textbf{Variable type: numeric}
\begin{longtable}[]{@{}
>{\raggedright\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.1867}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.1333}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.1867}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0800}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0667}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0400}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0533}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0533}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0533}}
>{\raggedleft\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0667}}
>{\raggedright\arraybackslash}p{(\columnwidth - 20\tabcolsep) * \real{0.0800}}@{}}
\toprule()
\begin{minipage}[b]{\linewidth}\raggedright
skim\_variable
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
n\_missing
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
complete\_rate
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
mean
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
sd
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
p0
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
p25
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
p50
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
p75
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedleft
p100
\end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
hist
\end{minipage} \\
\midrule()
\endhead
grade & 0 & 1 & 90.64 & 6.11 & 70 & 90 & 90 & 94 & 100 & ▁▂▁▇▃ \\
\bottomrule()
\end{longtable}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{summary}\NormalTok{(df)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
grade publication text date
Min. : 70.00 Length:107 Length:107 Min. :2020-03-16
1st Qu.: 90.00 Class :character Class :character 1st Qu.:2020-03-16
Median : 90.00 Mode :character Mode :character Median :2020-03-23
Mean : 90.64 Mean :2020-03-25
3rd Qu.: 94.00 3rd Qu.:2020-04-02
Max. :100.00 Max. :2020-05-01
\end{verbatim}
\hypertarget{python-5}{%
\subsubsection{Python}\label{python-5}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{df.info()}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 107 entries, 0 to 106
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 grade 107 non-null int64
1 publication 107 non-null object
2 text 107 non-null object
3 date 107 non-null object
dtypes: int64(1), object(3)
memory usage: 3.5+ KB
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{df.describe()}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
grade
count 107.000000
mean 90.635514
std 6.114308
min 70.000000
25% 90.000000
50% 90.000000
75% 94.000000
max 100.000000
\end{verbatim}
\hypertarget{semi-structured-data}{%
\chapter{Semi-structured Data}\label{semi-structured-data}}
When we talk about semi-structured data we usually refer to data that is
not represented as a table, but as a hierarchical nested structure of
key-value pairs. We will see how to import two kinds of file:
\begin{itemize}
\tightlist
\item
JSON (JavaScript Object Notation);
\item
XML (eXtensible Markup Language).
\end{itemize}
\hypertarget{r-6}{%
\subsubsection{R}\label{r-6}}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(jsonlite)}
\FunctionTok{library}\NormalTok{(xml2)}
\end{Highlighting}
\end{Shaded}
\hypertarget{python-6}{%
\subsubsection{Python}\label{python-6}}
\begin{Shaded}
\begin{Highlighting}[]
\ImportTok{import}\NormalTok{ pandas }\ImportTok{as}\NormalTok{ pd}
\end{Highlighting}
\end{Shaded}
\hypertarget{json}{%
\section{JSON}\label{json}}
We will use the \href{https://openlibrary.org/}{Open Library} RESTful
API (see chapter XX to know more about APIs) in order to retrieve
information about books written by one of my favorite authors,
\href{https://en.wikipedia.org/wiki/Anna_Maria_Ortese}{Anna Maria
Ortese}.
\hypertarget{r-7}{%
\subsubsection{R}\label{r-7}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{json\_data }\OtherTok{\textless{}{-}} \FunctionTok{read\_json}\NormalTok{(}\StringTok{"http://openlibrary.org/search.json?author=anna+maria+ortese"}\NormalTok{,}
\AttributeTok{simplifyVector =} \ConstantTok{TRUE}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\hypertarget{python-7}{%
\subsubsection{Python}\label{python-7}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{json\_data }\OperatorTok{=}\NormalTok{ pd.read\_json(}\StringTok{"http://openlibrary.org/search.json?author=anna+maria+ortese"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
By default, \texttt{jsonlite::read\_json()} will not simplify the JSON
structure, whereas \texttt{pd.read\_json()} will try to convert the JSON
file into a table.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{lapply}\NormalTok{(json\_data, length) }\CommentTok{\# in R}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
$numFound
[1] 1
$start
[1] 1
$numFoundExact
[1] 1
$docs
[1] 56
$num_found
[1] 1
$q
[1] 1
$offset
[1] 0
\end{verbatim}
We are interested in retrieving information from four sub-fields coming
from the \texttt{docs} field:
\hypertarget{r-8}{%
\subsubsection{R}\label{r-8}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{json\_data}\SpecialCharTok{$}\NormalTok{docs }\SpecialCharTok{|\textgreater{}}
\NormalTok{ dplyr}\SpecialCharTok{::}\FunctionTok{select}\NormalTok{(author\_name, title, publish\_year, number\_of\_pages\_median) }\SpecialCharTok{|\textgreater{}}