Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

R Programming for Data Science 1st

Edition Roger Peng


Visit to download the full and correct content document:
https://textbookfull.com/product/r-programming-for-data-science-1st-edition-roger-pen
g/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Functional Programming in R: Advanced Statistical


Programming for Data Science, Analysis and Finance 1st
Edition Thomas Mailund

https://textbookfull.com/product/functional-programming-in-r-
advanced-statistical-programming-for-data-science-analysis-and-
finance-1st-edition-thomas-mailund/

Advanced Object-Oriented Programming in R: Statistical


Programming for Data Science, Analysis and Finance 1st
Edition Thomas Mailund

https://textbookfull.com/product/advanced-object-oriented-
programming-in-r-statistical-programming-for-data-science-
analysis-and-finance-1st-edition-thomas-mailund/

Metaprogramming in R: Advanced Statistical Programming


for Data Science, Analysis and Finance 1st Edition
Thomas Mailund

https://textbookfull.com/product/metaprogramming-in-r-advanced-
statistical-programming-for-data-science-analysis-and-
finance-1st-edition-thomas-mailund/

R for Data Science 1st Edition Garrett Grolemund

https://textbookfull.com/product/r-for-data-science-1st-edition-
garrett-grolemund/
Programming Skills for Data Science 1st Edition Michael
Freeman

https://textbookfull.com/product/programming-skills-for-data-
science-1st-edition-michael-freeman/

Beginning Data Science in R: Data Analysis,


Visualization, and Modelling for the Data Scientist 1st
Edition Thomas Mailund

https://textbookfull.com/product/beginning-data-science-in-r-
data-analysis-visualization-and-modelling-for-the-data-
scientist-1st-edition-thomas-mailund/

Functional Data Structures in R: Advanced Statistical


Programming in R Mailund

https://textbookfull.com/product/functional-data-structures-in-r-
advanced-statistical-programming-in-r-mailund/

Advanced R: Data Programming and the Cloud 1st Edition


Matt Wiley

https://textbookfull.com/product/advanced-r-data-programming-and-
the-cloud-1st-edition-matt-wiley/

Doing Data Science in R An Introduction for Social


Scientists 1st Edition Mark Andrews

https://textbookfull.com/product/doing-data-science-in-r-an-
introduction-for-social-scientists-1st-edition-mark-andrews/
R Programming for Data Science
Roger D. Peng
This book is for sale at http://leanpub.com/rprogramming

This version was published on 2019-12-11

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

© 2014 - 2019 Roger D. Peng


Also By Roger D. Peng
The Art of Data Science
Exploratory Data Analysis with R
Executive Data Science
Report Writing for Data Science in R
Advanced Statistical Computing
The Data Science Salon
Conversations On Data Science
Mastering Software Development in R
Essays on Data Analysis
Contents

1. Stay in Touch! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

3. History and Overview of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5


3.1 What is R? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 What is S? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.3 The S Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.4 Back to R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.5 Basic Features of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.6 Free Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.7 Design of the R System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.8 Limitations of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.9 R Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

4. Getting Started with R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12


4.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 Getting started with the R interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

5. R Nuts and Bolts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13


5.1 Entering Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.3 R Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5.4 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.6 Creating Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.7 Mixing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.8 Explicit Coercion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.9 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.10 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.11 Factors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.12 Missing Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.13 Data Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.14 Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.15 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
CONTENTS

6. Getting Data In and Out of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24


6.1 Reading and Writing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.2 Reading Data Files with read.table() . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.3 Reading in Larger Datasets with read.table . . . . . . . . . . . . . . . . . . . . . . . . 25
6.4 Calculating Memory Requirements for R Objects . . . . . . . . . . . . . . . . . . . . . 26

7. Using the readr Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

8. Using Textual and Binary Formats for Storing Data . . . . . . . . . . . . . . . . . . . . . . 32


8.1 Using dput() and dump() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
8.2 Binary Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

9. Interfaces to the Outside World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36


9.1 File Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
9.2 Reading Lines of a Text File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
9.3 Reading From a URL Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

10. Subsetting R Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39


10.1 Subsetting a Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
10.2 Subsetting a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
10.3 Subsetting Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
10.4 Subsetting Nested Elements of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
10.5 Extracting Multiple Elements of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
10.6 Partial Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
10.7 Removing NA Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

11. Vectorized Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46


11.1 Vectorized Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

12. Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


12.1 Dates in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
12.2 Times in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
12.3 Operations on Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
12.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

13. Managing Data Frames with the dplyr package . . . . . . . . . . . . . . . . . . . . . . . . . 52


13.1 Data Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
13.2 The dplyr Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
13.3 dplyr Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
13.4 Installing the dplyr package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
13.5 select() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
13.6 filter() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
13.7 arrange() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
13.8 rename() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
13.9 mutate() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
CONTENTS

13.10 group_by() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60


13.11 %>% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
62
13.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

14. Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65


14.1 if-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
14.2 for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
14.3 Nested for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
14.4 while Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
14.5 repeat Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
14.6 next, break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
14.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

15. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
15.1 Functions in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
15.2 Your First Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
15.3 Argument Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
15.4 Lazy Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
15.5 The ... Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
15.6 Arguments Coming After the ... Argument . . . . . . . . . . . . . . . . . . . . . . . 79
15.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

16. Scoping Rules of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81


16.1 A Diversion on Binding Values to Symbol . . . . . . . . . . . . . . . . . . . . . . . . . 81
16.2 Scoping Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
16.3 Lexical Scoping: Why Does It Matter? . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
16.4 Lexical vs. Dynamic Scoping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
16.5 Application: Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
16.6 Plotting the Likelihood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
16.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

17. Coding Standards for R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

18. Loop Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93


18.1 Looping on the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
18.2 lapply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
18.3 sapply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
18.4 split() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
18.5 Splitting a Data Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
18.6 tapply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
18.7 apply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
18.8 Col/Row Sums and Means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
18.9 Other Ways to Apply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
18.10 mapply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
CONTENTS

18.11 Vectorizing a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109


18.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

19. Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111


19.1 Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
19.2 Primary R Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
19.3 grep() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
19.4 grepl() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
19.5 regexpr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
19.6 sub() and gsub() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
19.7 regexec() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
19.8 The stringr Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
19.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

20. Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124


20.1 Something’s Wrong! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
20.2 Figuring Out What’s Wrong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
20.3 Debugging Tools in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
20.4 Using traceback() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
20.5 Using debug() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
20.6 Using recover() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
20.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

21. Profiling R Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132


21.1 Using system.time() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
21.2 Timing Longer Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
21.3 The R Profiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
21.4 Using summaryRprof() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
21.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

22. Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138


22.1 Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
22.2 Setting the random number seed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
22.3 Simulating a Linear Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
22.4 Random Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
22.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

23. Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. . . . . . . 148
23.1 Synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
23.2 Loading and Processing the Raw Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
23.3 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

24. Parallel Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158


24.1 Hidden Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
CONTENTS

24.2 Embarrassing Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160


24.3 The Parallel Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
24.4 Example: Bootstrapping a Statistic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
24.5 Building a Socket Cluster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
24.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

25. Why I Indent My Code 8 Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

26. About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176


1. Stay in Touch!
Thanks for purchasing this book. If you are interested in hearing more from me about things that
I’m working on (books, data science courses, podcast, etc.), I have a regular podcast called Not So
Standard Deviations¹ that I co-host with Dr. Hilary Parker, a Data Scientist at Stitch Fix. On this
podcast, Hilary and I talk about the craft of data science and discuss common issues and problems
in analyzing data. We’ll also compare how data science is approached in both academia and industry
contexts and discuss the latest industry trends. You can listen to recent episodes on our web page or
you can subscribe to it in iTunes² or your favorite podcasting app.
For those of you who purchased a printed copy of this book, I encourage you to go to the Leanpub
web site and obtain the e-book version³, which is available for free. The reason is that I will
occasionally update the book with new material and readers who purchase the e-book version are
entitled to free updates (this is unfortunately not yet possible with printed books).
Thanks again for purchasing this book and please do stay in touch!
¹http://nssdeviations.com
²https://itunes.apple.com/us/podcast/not-so-standard-deviations/id1040614570
³https://leanpub.com/rprogramming
2. Preface
I started using R in 1998 when I was a college undergraduate working on my senior thesis.
The version was 0.63. I was an applied mathematics major with a statistics concentration and
I was working with Dr. Nicolas Hengartner on an analysis of word frequencies in classic texts
(Shakespeare, Milton, etc.). The idea was to see if we could identify the authorship of each of the
texts based on how frequently they used certain words. We downloaded the data from Project
Gutenberg and used some basic linear discriminant analysis for the modeling. The work was
eventually published¹ and was my first ever peer-reviewed publication. I guess you could argue
it was my first real “data science” experience.
Back then, no one was using R. Most of my classes were taught with Minitab, SPSS, Stata, or
Microsoft Excel. The cool people on the cutting edge of statistical methodology used S-PLUS. I
was working on my thesis late one night and I had a problem. I didn’t have a copy of any of those
software packages because they were expensive and I was a student. I didn’t feel like trekking over
to the computer lab to use the software because it was late at night.
But I had the Internet! After a couple of Yahoo! searches I found a web page for something called R,
which I figured was just a play on the name of the S-PLUS package. From what I could tell, R was a
“clone” of S-PLUS that was free. I had already written some S-PLUS code for my thesis so I figured
I would try to download R and see if I could just run the S-PLUS code.
It didn’t work. At least not at first. It turns out that R is not exactly a clone of S-PLUS and quite a few
modifications needed to be made before the code would run in R. In particular, R was missing a lot of
statistical functionality that had existed in S-PLUS for a long time already. Luckily, R’s programming
language was pretty much there and I was able to more or less re-implement the features that were
missing in R.
After college, I enrolled in a PhD program in statistics at the University of California, Los Angeles.
At the time the department was brand new and they didn’t have a lot of policies or rules (or classes,
for that matter!). So you could kind of do what you wanted, which was good for some students and
not so good for others. The Chair of the department, Jan de Leeuw, was a big fan of XLisp-Stat and
so all of the department’s classes were taught using XLisp-Stat. I diligently bought my copy of Luke
Tierney’s book² and learned to really love XLisp-Stat. It had a number of features that R didn’t have
at all, most notably dynamic graphics.
But ultimately, there were only so many parentheses that I could type, and still all of the research-
level statistics was being done in S-PLUS. The department didn’t really have a lot of copies of S-PLUS
lying around so I turned back to R. When I looked around at my fellow students, I realized that I
was basically the only one who had any experience using R. Since there was a budding interest in R
¹http://amstat.tandfonline.com/doi/abs/10.1198/000313002100#.VQGiSELpagE
²http://www.amazon.com/LISP-STAT-Object-Oriented-Environment-Statistical-Probability/dp/0471509167/
Preface 3

around the department, I decided to start a “brown bag” series where every week for about an hour
I would talk about something you could do in R (which wasn’t much, really). People seemed to like
it, if only because there wasn’t really anyone to turn to if you wanted to learn about R.
By the time I left grad school in 2003, the department had essentially switched over from XLisp-
Stat to R for all its work (although there were a few hold outs). Jan discusses the rationale for the
transition in a paper³ in the Journal of Statistical Software.
In the next step of my career, I went to the Department of Biostatistics⁴ at the Johns Hopkins
Bloomberg School of Public Health, where I have been for the past 16 years. When I got to Johns
Hopkins people already seemed into R. Most people had abandoned S-PLUS a while ago and were
committed to using R for their research. Of all the available statistical packages, R had the most
powerful and expressive programming language, which was perfect for someone developing new
statistical methods.
However, we didn’t really have a class that taught students how to use R. This was a problem because
most of our grad students were coming into the program having never heard of R. Most likely in
their undergraduate programs, they used some other software package. So along with Rafael Irizarry,
Brian Caffo, Ingo Ruczinski, and Karl Broman, I started a new class to teach our graduate students
R and a number of other skills they’d need in grad school.
The class was basically a weekly seminar where one of us talked about a computing topic of interest.
I gave some of the R lectures in that class and when I asked people who had heard of R before, almost
no one raised their hand. And no one had actually used it before. The main selling point at the time
was “It’s just like S-PLUS but it’s free!” A lot of people had experience with SAS or Stata or SPSS.
A number of people had used something like Java or C/C++ before and so I often used that as a
reference frame. No one had ever used a functional-style of programming language like Scheme or
Lisp.
To this day, I still teach the class, known a Biostatistics 140.776 (“Statistical Computing”). However,
the nature of the class has changed quite a bit over the years. The population of students (mostly
first-year graduate students) has shifted to the point where many of them have been introduced to R
as undergraduates. This trend mirrors the overall trend with statistics where we are seeing more and
more students do undergraduate majors in statistics (as opposed to, say, mathematics). Eventually,
by 2008–2009, when I’d asked how many people had heard of or used R before, everyone raised
their hand. However, even at that late date, I still felt the need to convince people that R was a “real”
language that could be used for real tasks.
R has grown a lot in recent years, and is being used in so many places now, that I think it’s
essentially impossible for a person to keep track of everything that is going on. That’s fine, but
it makes “introducing” people to R an interesting experience. Nowadays in class, students are often
teaching me something new about R that I’ve never seen or heard of before (they are quite good
at Googling around for themselves). I feel no need to “bring people over” to R. In fact it’s quite the
opposite–people might start asking questions if I weren’t teaching R.
³http://www.jstatsoft.org/v13/i07
⁴http://www.biostat.jhsph.edu
Preface 4

This book comes from my experience teaching R in a variety of settings and through different stages
of its (and my) development. Much of the material has been taken from by Statistical Computing
class as well as the R Programming⁵ class I teach through Coursera.
I’m looking forward to teaching R to people as long as people will let me, and I’m interested in
seeing how the next generation of students will approach it (and how my approach to them will
change). Overall, it’s been just an amazing experience to see the widespread adoption of R over the
past decade. I’m sure the next decade will be just as amazing.
⁵https://www.coursera.org/course/rprog
3. History and Overview of R
There are only two kinds of languages: the ones people complain about and the ones
nobody uses —Bjarne Stroustrup

Watch a video of this chapter¹

3.1 What is R?
This is an easy question to answer. R is a dialect of S.

3.2 What is S?
S is a language that was developed by John Chambers and others at the old Bell Telephone
Laboratories, originally part of AT&T Corp. S was initiated in 1976² as an internal statistical analysis
environment—originally implemented as Fortran libraries. Early versions of the language did not
even contain functions for statistical modeling.
In 1988 the system was rewritten in C and began to resemble the system that we have today (this
was Version 3 of the language). The book Statistical Models in S by Chambers and Hastie (the white
book) documents the statistical analysis functionality. Version 4 of the S language was released in
1998 and is the version we use today. The book Programming with Data by John Chambers (the
green book) documents this version of the language.
Since the early 90’s the life of the S language has gone down a rather winding path. In 1993 Bell Labs
gave StatSci (later Insightful Corp.) an exclusive license to develop and sell the S language. In 2004
Insightful purchased the S language from Lucent for $2 million. In 2006, Alcatel purchased Lucent
Technologies and is now called Alcatel-Lucent.
Insightful sold its implementation of the S language under the product name S-PLUS and built a
number of fancy features (GUIs, mostly) on top of it—hence the “PLUS”. In 2008 Insightful was
acquired by TIBCO for $25 million. As of this writing TIBCO is the current owner of the S language
and is its exclusive developer.
The fundamentals of the S language itself has not changed dramatically since the publication of the
Green Book by John Chambers in 1998. In 1998, S won the Association for Computing Machinery’s
Software System Award, a highly prestigious award in the computer science field.
¹https://youtu.be/STihTnVSZnI
²http://cm.bell-labs.com/stat/doc/94.11.ps
History and Overview of R 6

3.3 The S Philosophy


The general S philosophy is important to understand for users of S and R because it sets the stage for
the design of the language itself, which many programming veterans find a bit odd and confusing.
In particular, it’s important to realize that the S language had its roots in data analysis, and did not
come from a traditional programming language background. Its inventors were focused on figuring
out how to make data analysis easier, first for themselves, and then eventually for others.
In Stages in the Evolution of S³, John Chambers writes:

“[W]e wanted users to be able to begin in an interactive environment, where they did not
consciously think of themselves as programming. Then as their needs became clearer and
their sophistication increased, they should be able to slide gradually into programming,
when the language and system aspects would become more important.”

The key part here was the transition from user to developer. They wanted to build a language that
could easily service both “people”. More technically, they needed to build language that would
be suitable for interactive data analysis (more command-line based) as well as for writing longer
programs (more traditional programming language-like).

3.4 Back to R
The R language came to use quite a bit after S had been developed. One key limitation of the S
language was that it was only available in a commericial package, S-PLUS. In 1991, R was created
by Ross Ihaka and Robert Gentleman in the Department of Statistics at the University of Auckland. In
1993 the first announcement of R was made to the public. Ross’s and Robert’s experience developing
R is documented in a 1996 paper in the Journal of Computational and Graphical Statistics:

Ross Ihaka and Robert Gentleman. R: A language for data analysis and graphics. Journal
of Computational and Graphical Statistics, 5(3):299–314, 1996

In 1995, Martin Mächler made an important contribution by convincing Ross and Robert to use the
GNU General Public License⁴ to make R free software. This was critical because it allowed for the
source code for the entire R system to be accessible to anyone who wanted to tinker with it (more
on free software later).
In 1996, a public mailing list was created (the R-help and R-devel lists) and in 1997 the R Core
Group was formed, containing some people associated with S and S-PLUS. Currently, the core group
controls the source code for R and is solely able to check in changes to the main R source tree. Finally,
in 2000 R version 1.0.0 was released to the public.
³http://www.stat.bell-labs.com/S/history.html
⁴http://www.gnu.org/licenses/gpl-2.0.html
History and Overview of R 7

3.5 Basic Features of R


In the early days, a key feature of R was that its syntax is very similar to S, making it easy for
S-PLUS users to switch over. While the R’s syntax is nearly identical to that of S’s, R’s semantics,
while superficially similar to S, are quite different. In fact, R is technically much closer to the Scheme
language than it is to the original S language when it comes to how R works under the hood.
Today R runs on almost any standard computing platform and operating system. Its open source
nature means that anyone is free to adapt the software to whatever platform they choose. Indeed, R
has been reported to be running on modern tablets, phones, PDAs, and game consoles.
One nice feature that R shares with many popular open source projects is frequent releases. These
days there is a major annual release, typically in October, where major new features are incorporated
and released to the public. Throughout the year, smaller-scale bugfix releases will be made as needed.
The frequent releases and regular release cycle indicates active development of the software and
ensures that bugs will be addressed in a timely manner. Of course, while the core developers control
the primary source tree for R, many people around the world make contributions in the form of new
feature, bug fixes, or both.
Another key advantage that R has over many other statistical packages (even today) is its sophisti-
cated graphics capabilities. R’s ability to create “publication quality” graphics has existed since the
very beginning and has generally been better than competing packages. Today, with many more
visualization packages available than before, that trend continues. R’s base graphics system allows
for very fine control over essentially every aspect of a plot or graph. Other newer graphics systems,
like lattice and ggplot2 allow for complex and sophisticated visualizations of high-dimensional data.
R has maintained the original S philosophy, which is that it provides a language that is both useful
for interactive work, but contains a powerful programming language for developing new tools. This
allows the user, who takes existing tools and applies them to data, to slowly but surely become a
developer who is creating new tools.
Finally, one of the joys of using R has nothing to do with the language itself, but rather with the
active and vibrant user community. In many ways, a language is successful inasmuch as it creates a
platform with which many people can create new things. R is that platform and thousands of people
around the world have come together to make contributions to R, to develop packages, and help
each other use R for all kinds of applications. The R-help and R-devel mailing lists have been highly
active for over a decade now and there is considerable activity on web sites like Stack Overflow.

3.6 Free Software


A major advantage that R has over many other statistical packages and is that it’s free in the sense
of free software (it’s also free in the sense of free beer). The copyright for the primary source code
for R is held by the R Foundation⁵ and is published under the GNU General Public License version
⁵http://www.r-project.org/foundation/
History and Overview of R 8

2.0⁶.
According to the Free Software Foundation, with free software, you are granted the following four
freedoms⁷

• The freedom to run the program, for any purpose (freedom 0).
• The freedom to study how the program works, and adapt it to your needs (freedom 1). Access
to the source code is a precondition for this.
• The freedom to redistribute copies so you can help your neighbor (freedom 2).
• The freedom to improve the program, and release your improvements to the public, so that the
whole community benefits (freedom 3). Access to the source code is a precondition for this.

You can visit the Free Software Foundation’s web site⁸ to learn a lot more about free software. The
Free Software Foundation was founded by Richard Stallman in 1985 and Stallman’s personal web
site⁹ is an interesting read if you happen to have some spare time.

3.7 Design of the R System


The primary R system is available from the Comprehensive R Archive Network¹⁰, also known as
CRAN. CRAN also hosts many add-on packages that can be used to extend the functionality of R.
The R system is divided into 2 conceptual parts:

1. The “base” R system that you download from CRAN: Linux¹¹ Windows¹² Mac¹³ Source Code¹⁴
2. Everything else.

R functionality is divided into a number of packages.

• The “base” R system contains, among other things, the base package which is required to run
R and contains the most fundamental functions.
• The other packages contained in the “base” system include utils, stats, datasets, graphics,
grDevices, grid, methods, tools, parallel, compiler, splines, tcltk, stats4.
• There are also “Recommended” packages: boot, class, cluster, codetools, foreign, KernS-
mooth, lattice, mgcv, nlme, rpart, survival, MASS, spatial, nnet, Matrix.
⁶http://www.gnu.org/licenses/gpl-2.0.html
⁷http://www.gnu.org/philosophy/free-sw.html
⁸http://www.fsf.org
⁹https://stallman.org
¹⁰http://cran.r-project.org
¹¹http://cran.r-project.org/bin/linux/
¹²http://cran.r-project.org/bin/windows/
¹³http://cran.r-project.org/bin/macosx/
¹⁴http://cran.r-project.org/src/base/R-3/R-3.1.3.tar.gz
History and Overview of R 9

When you download a fresh installation of R from CRAN, you get all of the above, which represents
a substantial amount of functionality. However, there are many other packages available:

• There are over 4000 packages on CRAN that have been developed by users and programmers
around the world.
• There are also many packages associated with the Bioconductor project¹⁵.
• People often make packages available on their personal websites; there is no reliable way to
keep track of how many packages are available in this fashion.
• There are a number of packages being developed on repositories like GitHub and BitBucket but
there is no reliable listing of all these packages.

3.8 Limitations of R
No programming language or statistical analysis system is perfect. R certainly has a number of
drawbacks. For starters, R is essentially based on almost 50 year old technology, going back to the
original S system developed at Bell Labs. There was originally little built in support for dynamic or
3-D graphics (but things have improved greatly since the “old days”).
Another commonly cited limitation of R is that objects must generally be stored in physical memory.
This is in part due to the scoping rules of the language, but R generally is more of a memory hog
than other statistical packages. However, there have been a number of advancements to deal with
this, both in the R core and also in a number of packages developed by contributors. Also, computing
power and capacity has continued to grow over time and amount of physical memory that can be
installed on even a consumer-level laptop is substantial. While we will likely never have enough
physical memory on a computer to handle the increasingly large datasets that are being generated,
the situation has gotten quite a bit easier over time.
At a higher level one “limitation” of R is that its functionality is based on consumer demand and
(voluntary) user contributions. If no one feels like implementing your favorite method, then it’s your
job to implement it (or you need to pay someone to do it). The capabilities of the R system generally
reflect the interests of the R user community. As the community has ballooned in size over the past
10 years, the capabilities have similarly increased. When I first started using R, there was very little
in the way of functionality for the physical sciences (physics, astronomy, etc.). However, now some
of those communities have adopted R and we are seeing more code being written for those kinds of
applications.
If you want to know my general views on the usefulness of R, you can see them here in the following
exchange on the R-help mailing list with Douglas Bates and Brian Ripley in June 2004:

Roger D. Peng: I don’t think anyone actually believes that R is designed to make everyone
happy. For me, R does about 99% of the things I need to do, but sadly, when I need to order
a pizza, I still have to pick up the telephone.
¹⁵http://bioconductor.org
History and Overview of R 10

Douglas Bates: There are several chains of pizzerias in the U.S. that provide for Internet-
based ordering (e.g. www.papajohnsonline.com) so, with the Internet modules in R, it’s
only a matter of time before you will have a pizza-ordering function available.

Brian D. Ripley: Indeed, the GraphApp toolkit (used for the RGui interface under R for
Windows, but Guido forgot to include it) provides one (for use in Sydney, Australia, we
presume as that is where the GraphApp author hails from). Alternatively, a Padovian has
no need of ordering pizzas with both home and neighbourhood restaurants ….

At this point in time, I think it would be fairly straightforward to build a pizza ordering R package
using something like the RCurl or httr packages. Any takers?

3.9 R Resources

Official Manuals
As far as getting started with R by reading stuff, there is of course this book. Also, available from
CRAN¹⁶ are

• An Introduction to R¹⁷
• R Data Import/Export¹⁸
• Writing R Extensions¹⁹: Discusses how to write and organize R packages
• R Installation and Administration²⁰: This is mostly for building R from the source code)
• R Internals²¹: This manual describes the low level structure of R and is primarily for developers
and R core members
• R Language Definition²²: This documents the R language and, again, is primarily for developers

Useful Standard Texts on S and R


• Chambers (2008). Software for Data Analysis, Springer
• Chambers (1998). Programming with Data, Springer: This book is not about R, but it describes
the organization and philosophy of the current version of the S language, and is a useful
reference.
• Venables & Ripley (2002). Modern Applied Statistics with S, Springer: This is a standard textbook
in statistics and describes how to use many statistical methods in R. This book has an associated
R package (the MASS package) that comes with every installation of R.
¹⁶http://cran.r-project.org
¹⁷http://cran.r-project.org/doc/manuals/r-release/R-intro.html
¹⁸http://cran.r-project.org/doc/manuals/r-release/R-data.html
¹⁹http://cran.r-project.org/doc/manuals/r-release/R-exts.html
²⁰http://cran.r-project.org/doc/manuals/r-release/R-admin.html
²¹http://cran.r-project.org/doc/manuals/r-release/R-ints.html
²²http://cran.r-project.org/doc/manuals/r-release/R-lang.html
History and Overview of R 11

• Venables & Ripley (2000). S Programming, Springer: This book is a little old but is still relevant
and accurate. Despite its title, this book is useful for R also.
• Murrell (2005). R Graphics, Chapman & Hall/CRC Press: Paul Murrell wrote and designed much
of the graphics system in R and this book essentially documents the underlying details. This
is not so much a “user-level” book as a developer-level book. But it is an important book for
anyone interested in designing new types of graphics or visualizations.
• Wickham (2014). Advanced R, Chapman & Hall/CRC Press: This book by Hadley Wickham
covers a number of areas including object-oriented programming, functional programming,
profiling and other advanced topics.

Other Resources
• Major technical publishers like Springer, Chapman & Hall/CRC have entire series of books
dedicated to using R in various applications. For example, Springer has a series of books called
Use R!.
• A longer list of books can be found on the CRAN web site²³.

²³http://www.r-project.org/doc/bib/R-books.html
4. Getting Started with R
4.1 Installation
The first thing you need to do to get started with R is to install it on your computer. R works on
pretty much every platform available, including the widely available Windows, Mac OS X, and Linux
systems. If you want to watch a step-by-step tutorial on how to install R for Mac or Windows, you
can watch these videos:

• Installing R on Windows¹
• Installing R on the Mac²

There is also an integrated development environment available for R that is built by RStudio. I really
like this IDE—it has a nice editor with syntax highlighting, there is an R object viewer, and there are
a number of other nice features that are integrated. You can see how to install RStudio here

• Installing RStudio³

The RStudio IDE is available from RStudio’s web site⁴.

4.2 Getting started with the R interface


After you install R you will need to launch it and start writing R code. Before we get to exactly how
to write R code, it’s useful to get a sense of how the system is organized. In these two videos I talk
about where to write code and how set your working directory, which let’s R know where to find
all of your files.

• Writing code and setting your working directory on the Mac⁵


• Writing code and setting your working directory on Windows⁶

¹http://youtu.be/Ohnk9hcxf9M
²https://youtu.be/uxuuWXU-7UQ
³https://youtu.be/bM7Sfz-LADM
⁴http://rstudio.com
⁵https://youtu.be/8xT3hmJQskU
⁶https://youtu.be/XBcvH1BpIBo
5. R Nuts and Bolts
5.1 Entering Input
Watch a video of this section¹
At the R prompt we type expressions. The <- symbol is the assignment operator.

> x <- 1
> print(x)
[1] 1
> x
[1] 1
> msg <- "hello"

The grammar of the language determines whether an expression is complete or not.

x <- ## Incomplete expression

The # character indicates a comment. Anything to the right of the # (including the # itself) is ignored.
This is the only comment character in R. Unlike some other languages, R does not support multi-line
comments or comment blocks.

5.2 Evaluation
When a complete expression is entered at the prompt, it is evaluated and the result of the evaluated
expression is returned. The result may be auto-printed.

> x <- 5 ## nothing printed


> x ## auto-printing occurs
[1] 5
> print(x) ## explicit printing
[1] 5

The [1] shown in the output indicates that x is a vector and 5 is its first element.
Typically with interactive work, we do not explicitly print objects with the print function; it is much
easier to just auto-print them by typing the name of the object and hitting return/enter. However,
¹https://youtu.be/vGY5i_J2c-c?t=4m43s
R Nuts and Bolts 14

when writing scripts, functions, or longer programs, there is sometimes a need to explicitly print
objects because auto-printing does not work in those settings.
When an R vector is printed you will notice that an index for the vector is printed in square brackets
[] on the side. For example, see this integer sequence of length 20.

> x <- 11:30


> x
[1] 11 12 13 14 15 16 17 18 19 20 21 22
[13] 23 24 25 26 27 28 29 30

The numbers in the square brackets are not part of the vector itself, they are merely part of the
printed output.
With R, it’s important that one understand that there is a difference between the actual R object
and the manner in which that R object is printed to the console. Often, the printed output may have
additional bells and whistles to make the output more friendly to the users. However, these bells and
whistles are not inherently part of the object.
Note that the : operator is used to create integer sequences.

5.3 R Objects
Watch a video of this section²
R has five basic or “atomic” classes of objects:

• character
• numeric (real numbers)
• integer
• complex
• logical (True/False)

The most basic type of R object is a vector. Empty vectors can be created with the vector() function.
There is really only one rule about vectors in R, which is that A vector can only contain objects
of the same class.
But of course, like any good rule, there is an exception, which is a list, which we will get to a bit later.
A list is represented as a vector but can contain objects of different classes. Indeed, that’s usually
why we use them.
There is also a class for “raw” objects, but they are not commonly used directly in data analysis and
I won’t cover them here.
²https://youtu.be/vGY5i_J2c-c
R Nuts and Bolts 15

5.4 Numbers
Numbers in R are generally treated as numeric objects (i.e. double precision real numbers). This
means that even if you see a number like “1” or “2” in R, which you might think of as integers, they
are likely represented behind the scenes as numeric objects (so something like “1.00” or “2.00”). This
isn’t important most of the time…except when it is.
If you explicitly want an integer, you need to specify the L suffix. So entering 1 in R gives you a
numeric object; entering 1L explicitly gives you an integer object.
There is also a special number Inf which represents infinity. This allows us to represent entities like
1 / 0. This way, Inf can be used in ordinary calculations; e.g. 1 / Inf is 0.

The value NaN represents an undefined value (“not a number”); e.g. 0 / 0; NaN can also be thought of
as a missing value (more on that later)

5.5 Attributes
R objects can have attributes, which are like metadata for the object. These metadata can be very
useful in that they help to describe the object. For example, column names on a data frame help to
tell us what data are contained in each of the columns. Some examples of R object attributes are

• names, dimnames
• dimensions (e.g. matrices, arrays)
• class (e.g. integer, numeric)
• length
• other user-defined attributes/metadata

Attributes of an object (if any) can be accessed using the attributes() function. Not all R objects
contain attributes, in which case the attributes() function returns NULL.

5.6 Creating Vectors


Watch a video of this section³
The c() function can be used to create vectors of objects by concatenating things together.

³https://youtu.be/w8_XdYI3reU
R Nuts and Bolts 16

> x <- c(0.5, 0.6) ## numeric


> x <- c(TRUE, FALSE) ## logical
> x <- c(T, F) ## logical
> x <- c("a", "b", "c") ## character
> x <- 9:29 ## integer
> x <- c(1+0i, 2+4i) ## complex

Note that in the above example, T and F are short-hand ways to specify TRUE and FALSE. However,
in general one should try to use the explicit TRUE and FALSE values when indicating logical values.
The T and F values are primarily there for when you’re feeling lazy.
You can also use the vector() function to initialize vectors.

> x <- vector("numeric", length = 10)


> x
[1] 0 0 0 0 0 0 0 0 0 0

5.7 Mixing Objects


There are occasions when different classes of R objects get mixed together. Sometimes this happens
by accident but it can also happen on purpose. So what happens with the following code?

> y <- c(1.7, "a") ## character


> y <- c(TRUE, 2) ## numeric
> y <- c("a", TRUE) ## character

In each case above, we are mixing objects of two different classes in a vector. But remember that
the only rule about vectors says this is not allowed. When different objects are mixed in a vector,
coercion occurs so that every element in the vector is of the same class.
In the example above, we see the effect of implicit coercion. What R tries to do is find a way to
represent all of the objects in the vector in a reasonable fashion. Sometimes this does exactly what
you want and…sometimes not. For example, combining a numeric object with a character object
will create a character vector, because numbers can usually be easily represented as strings.

5.8 Explicit Coercion


Objects can be explicitly coerced from one class to another using the as.* functions, if available.
R Nuts and Bolts 17

> x <- 0:6


> class(x)
[1] "integer"
> as.numeric(x)
[1] 0 1 2 3 4 5 6
> as.logical(x)
[1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE
> as.character(x)
[1] "0" "1" "2" "3" "4" "5" "6"

Sometimes, R can’t figure out how to coerce an object and this can result in NAs being produced.

> x <- c("a", "b", "c")


> as.numeric(x)
Warning: NAs introduced by coercion
[1] NA NA NA
> as.logical(x)
[1] NA NA NA
> as.complex(x)
Warning: NAs introduced by coercion
[1] NA NA NA

When nonsensical coercion takes place, you will usually get a warning from R.

5.9 Matrices
Matrices are vectors with a dimension attribute. The dimension attribute is itself an integer vector
of length 2 (number of rows, number of columns)

> m <- matrix(nrow = 2, ncol = 3)


> m
[,1] [,2] [,3]
[1,] NA NA NA
[2,] NA NA NA
> dim(m)
[1] 2 3
> attributes(m)
$dim
[1] 2 3

Matrices are constructed column-wise, so entries can be thought of starting in the “upper left” corner
and running down the columns.
R Nuts and Bolts 18

> m <- matrix(1:6, nrow = 2, ncol = 3)


> m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

Matrices can also be created directly from vectors by adding a dimension attribute.

> m <- 1:10


> m
[1] 1 2 3 4 5 6 7 8 9 10
> dim(m) <- c(2, 5)
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10

Matrices can be created by column-binding or row-binding with the cbind() and rbind() functions.

> x <- 1:3


> y <- 10:12
> cbind(x, y)
x y
[1,] 1 10
[2,] 2 11
[3,] 3 12
> rbind(x, y)
[,1] [,2] [,3]
x 1 2 3
y 10 11 12

5.10 Lists
Lists are a special type of vector that can contain elements of different classes. Lists are a very
important data type in R and you should get to know them well. Lists, in combination with the
various “apply” functions discussed later, make for a powerful combination.
Lists can be explicitly created using the list() function, which takes an arbitrary number of
arguments.
R Nuts and Bolts 19

> x <- list(1, "a", TRUE, 1 + 4i)


> x
[[1]]
[1] 1

[[2]]
[1] "a"

[[3]]
[1] TRUE

[[4]]
[1] 1+4i

We can also create an empty list of a prespecified length with the vector() function

> x <- vector("list", length = 5)


> x
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

5.11 Factors
Watch a video of this section⁴
Factors are used to represent categorical data and can be unordered or ordered. One can think of
a factor as an integer vector where each integer has a label. Factors are important in statistical
modeling and are treated specially by modelling functions like lm() and glm().
Using factors with labels is better than using integers because factors are self-describing. Having a
variable that has values “Male” and “Female” is better than a variable that has values 1 and 2.
Factor objects can be created with the factor() function.
⁴https://youtu.be/NuY6jY4qE7I
R Nuts and Bolts 20

> x <- factor(c("yes", "yes", "no", "yes", "no"))


> x
[1] yes yes no yes no
Levels: no yes
> table(x)
x
no yes
2 3
> ## See the underlying representation of factor
> unclass(x)
[1] 2 2 1 2 1
attr(,"levels")
[1] "no" "yes"

Often factors will be automatically created for you when you read a dataset in using a function like
read.table(). Those functions often default to creating factors when they encounter data that look
like characters or strings.
The order of the levels of a factor can be set using the levels argument to factor(). This can be
important in linear modelling because the first level is used as the baseline level.

> x <- factor(c("yes", "yes", "no", "yes", "no"))


> x ## Levels are put in alphabetical order
[1] yes yes no yes no
Levels: no yes
> x <- factor(c("yes", "yes", "no", "yes", "no"),
+ levels = c("yes", "no"))
> x
[1] yes yes no yes no
Levels: yes no

5.12 Missing Values


Missing values are denoted by NA or NaN for q undefined mathematical operations.

• is.na() is used to test objects if they are NA


• is.nan() is used to test for NaN
• NA values have a class also, so there are integer NA, character NA, etc.
• A NaN value is also NA but the converse is not true
R Nuts and Bolts 21

> ## Create a vector with NAs in it


> x <- c(1, 2, NA, 10, 3)
> ## Return a logical vector indicating which elements are NA
> is.na(x)
[1] FALSE FALSE TRUE FALSE FALSE
> ## Return a logical vector indicating which elements are NaN
> is.nan(x)
[1] FALSE FALSE FALSE FALSE FALSE

> ## Now create a vector with both NA and NaN values


> x <- c(1, 2, NaN, NA, 4)
> is.na(x)
[1] FALSE FALSE TRUE TRUE FALSE
> is.nan(x)
[1] FALSE FALSE TRUE FALSE FALSE

5.13 Data Frames


Data frames are used to store tabular data in R. They are an important type of object in R and
are used in a variety of statistical modeling applications. Hadley Wickham’s package dplyr⁵ has an
optimized set of functions designed to work efficiently with data frames.
Data frames are represented as a special type of list where every element of the list has to have the
same length. Each element of the list can be thought of as a column and the length of each element
of the list is the number of rows.
Unlike matrices, data frames can store different classes of objects in each column. Matrices must
have every element be the same class (e.g. all integers or all numeric).
In addition to column names, indicating the names of the variables or predictors, data frames have
a special attribute called row.names which indicate information about each row of the data frame.
Data frames are usually created by reading in a dataset using the read.table() or read.csv().
However, data frames can also be created explicitly with the data.frame() function or they can be
coerced from other types of objects like lists.
Data frames can be converted to a matrix by calling data.matrix(). While it might seem that the
as.matrix() function should be used to coerce a data frame to a matrix, almost always, what you
want is the result of data.matrix().

⁵https://github.com/hadley/dplyr
Another random document with
no related content on Scribd:
Parve un artifizio quella ritirata, tanto più che la minima resistenza
potea scompigliare il piccolo esercito francese quando appunto la
guerra volgeasi in peggio sul Reno, e la disobbedienza propagavasi
nell’esercito [7]: ma come si conobbe il vero, Lazzari capitano de’
Piemontesi fu sottoposto a consiglio di guerra e degradato, e
quest’esercito in tutta Europa tacciato di vile, prima che se ne
vedessero di ben più gagliardi e agguerriti fuggire davanti a quei
militari improvvisati. Perocchè la nazione intera si avventava alle
frontiere, e giovani eroi briachi d’entusiasmo introdussero una tattica
nuova, senza riguardi alle vite o ai disagi dell’uomo, nè quartieri
d’inverno, nè riposi da marcie, nè tende o baracche; sicchè davanti a
quel misto di generosità, di cupidigia, di terrore, che fu carattere
della Rivoluzione, anche i migliori ordini degli altri paesi dovettero
soccombere alla forza, divenuta supremo movente. Poco andò che
anche Nizza fu presa, e scrittovi sulla cattedrale Temple de la raison;
e nella festa del 10 agosto 1793 si diede il volo ad uccelli che
portavano l’atto costituzionale, per annunziare al mondo la fraternità
francese.
Dall’invasa Savoja, i rifuggiti, soliti sparnazzatori di vanti e di
sgomenti, fuggirono a torme sopra Torino: ma sebbene l’esercito
fosse sfasciato, le popolazioni avverse ai Giacobini sfogavansi in
vendette; e coll’antico nome di Barbetti, masnade assalivano e
trucidavano alla spicciolata i Francesi nelle montagne nizzarde. Sul
mare, Oneglia era centro della pirateria contro la Francia: ma
avendo percosso una nave mandata con proposizioni, l’ammiraglio
Truguet la bombardò (1792); tutta la gente fuggì, eccetto i frati che si
credeano inviolabili, e che furono tutti trucidati, ed arsa la città.
I grossi capitali che i suoi negozianti aveano in Francia, obbligavano
la repubblica di Genova a circospezione; d’altra parte unirsi al
Piemonte non osava, sapendone la lunga cupidigia; non all’Austria,
di cui aveva spezzato i ferri; talchè teneasi di mezzo fra le
pretensioni opposte di Parigi e di Londra. Quest’ultima, abusando
della marittima superiorità, sorprese in porto la Modesta, fregata
francese, e mandò intimare ai Genovesi cessassero ogni
comunicazione con Francia, e non ne ricevessero veruna nave:
prepotenza inaudita! Poi i Côrsi, alzata bandiera inglese, sfogavano
l’odio antico, corseggiando sulle coste.
Essendo chiuso dagl’Inglesi il porto di Genova, la Toscana avrebbe
potuto vantaggiarsi collo spedire olj, saponi, grani in Francia: ma
Inghilterra le intimò cacciasse tutti i Francesi (11 8bre) e anche
l’ambasciadore entro quarantott’ore; e il granduca, avuta garanzia
de’ suoi Stati da quella potenza, abbandonò la politica d’interesse
per quella di sentimento, e armò, rinnovando la milizia paesana al
modo del Machiavelli.
Anche Napoli, malgrado la neutralità stipulata colla Francia, promise
unire alle forze inglesi seimila uomini, quattro vascelli di linea e
quattro minori ed altrettante fregate e più occorrendo; impedire ogni
commercio colla Francia, aprendo invece i porti (12 luglio) alle navi
inglesi. Difatto le napoletane corsero colle flotte alleate a predare il
ricchissimo arsenale francese di Tolone; ma trovandolo difeso da
Napoleone Buonaparte, dovettero ritornarsene con molto spesa e
nessun profitto, per propria scusa esagerando il valore e la fierezza
de’ Francesi. Subito il re rifece l’esercito, e Acton e Carolina
vigilavano personalmente, animavano, faceasi denaro di tutto.
Quando poi Montesquiou, conquistatore della Savoja, fu destituito
(1794) dalla repubblica perchè mettea freno ai patriotici assassinj de’
Nizzardi, e le arcadiche atrocità di Robespierre esacerbarono sì che
parea le popolazioni si rivolterebbero contro la tirannide de’
Terroristi, la coalizione si rannodò col disegno d’invadere la Francia.
Per verità, il Piemonte se avesse concentrate le forze s’un punto
solo, e preso accordo coi Lionesi, coi Provenzali, cogli altri Girondini
e Federalisti, avrebbe sostenuto la prima figura in quei tentativi, e
fors’anche mutato le sorti di Francia [8]. Ma re Vittorio, di molto
coraggio e niun’abilità, preferì distendere le sue truppe lungo la
frontiera in aspetto di difesa, e aborrendo dallo stendere la mano agli
uccisori di suo cognato, preferiva operare di conserva coll’Austria,
colla quale a Valenciennes (23 maggio) convenne sulle spartizioni; i
paesi che si togliessero a Francia verso Italia, cadrebbero al re in
compenso d’altri verso il Milanese ch’e’ cederebbe all’imperatore.
Ma anche nell’esercito piemontese diffondeansi i dogmi rivoluzionarj,
propagatore principale il côrso Cervoni, che per compenso fu poi
eletto a generale di brigata nell’esercito italiano. I Sardi si erano
valorosamente schermiti da’ Francesi; ma non per questo
rassegnavansi all’oppressione piemontese, e spedirono una
deputazione dei tre ordini a Torino, domandando fossero levati molti
abusi, mantenuti i privilegi, raccolti gli stamenti. La Corte la trattenne
lungamente a Oneglia, poi permessole di venire, sei mesi le tardò
udienza, infine non diè che parole (1793 28 aprile). Avutolo per un
oltraggio, Cagliari insorge, nè la forza basta a reprimere; il vicerè e
l’arcivescovo partono, s’adunano dappertutto gli stamenti, e si
rinviano i Piemontesi impiegati e i vescovi; poi subito i contadini
ricusano le prestazioni ai baroni, la demagogia gavazza fra disordini
e sangue; e tutto è peggiorato dalle rivalità degli Angiò e dei Petzolo.
Così l’Italia era disunita e fiacca; intanto che la Francia, tuffata la
guerra intestina in un mare di sangue, spediva Kellermann (1793),
che con cinquantamila uomini rincacciò i Piemontesi, tornati nella
Savoja; un altro esercito per la riviera invade Ventimiglia e Oneglia;
altri Francesi versavansi dal Cenisio sul Piemonte, non rattenuti che
dal forte della Brunetta; e le creste delle Alpi e degli Appennini
divennero teatro di fiere battaglie, dove il valore piemontese riscattò
gli smacchi della prima campagna, respingendo anche più volte i
Francesi. Ma questi procedeano; presero anche l’inespugnabile
Saorgio e Col di Tenda. I re, tentennanti di paura, moltiplicano
minaccie, arrestano, uccidono, raddoppiano di vigilanza, interdicono
ogni convegno anche letterario. Ma dal re di Napoli non si possono
ripromettere soccorsi, perchè ha il fuoco in casa: all’Austria, paga di
avere assicurata la sua Lombardia dall’invasione, poco caleva che re
Vittorio recuperasse i territorj perduti, e mentre accalorava le
imprese in Fiandra, qui spediva solo pochi reggimenti comandati dal
barone Devins, buon allievo di Laudon, ma vecchio, podagroso,
avaro, mentre vecchio e malaticcio pur era il barone Colli, austriaco
nato a Vigevano, che ferito nel petto a Belgrado, doveva farsi portare
in lettiga, eppure era stato chiamato a capitanare le armi
piemontesi [9]. Francia senza perder tempo assale gli alleati nel
campo di Dego, li riduce a ritirarsi, e baldanzosamente spiega la
bandiera tricolore sulle Alpi marittime e sulle savojarde, a guisa di
turbine addensato sulle vette minacciando la sbigottita Italia.
CAPITOLO CLXXVI.
Buonaparte in Italia. I Giacobini. Fine di
Venezia.

Ogni rivoluzione divora i proprj figli; e come i monarchici erano stati


uccisi dai costituzionali, poi i costituzionali dai repubblicanti, e questi
dai puritani, e tutti dai terroristi, così venne il giorno che anche i
teschi ferini di Danton, Robespierre, Carrier furono gettati nella
pozza del sangue da loro versato (1794 luglio). Allora in Francia si
osò mostrare umanità e quasi anche giustizia, a qualche innocente
aprire le carceri, perdonare, permettere fino il culto; i moderati
ripresero aura; i tanti arricchiti coi beni nazionali, colle forniture, colle
eredità cascate dalla ghigliottina, col disordine ove sempre
guadagnano gli scaltri, bramavano godere dopo tante privazioni e
tanti sgomenti; sicchè invocavasi fine alle stragi, riposo dalle
sanguinarie convulsioni. Ma poichè a quel terribile agguagliamento
non era sopravvissuta che la forza, alla forza si dovette ricorrere per
disarmare la plebaglia (1795) e trucidare i Giacobini più ostinati: nel
che alla vigorìa di Barras servì l’inesorabile mitraglia del Buonaparte,
richiamato dalle Alpi alla caduta di Robespierre. Allora si stabilì una
nuova costituzione che tutelasse le acquistate libertà e la repubblica
una ed indivisibile (9bre); visto che una Camera sola facilmente
diveniva precipitosa e violenta, si volle associare la ragione e
l’immaginazione istituendo un Consiglio di cinquecento persone,
almeno trentenni, rinnovatesi per terzo ogn’anno; ed uno di
ducencinquanta anziani sopra i quarant’anni, ammogliati o vedovi,
rinnovatesi al modo stesso, che sanzionava le leggi proposte da
quelli, ma che poteano discutersi soltanto dopo tre letture. Tutti i
cittadini, dai ventun anno in su, nelle assemblee primarie nominano i
membri delle assemblee elettorali, che eleggono i due Consigli, e
questi il Direttorio esecutivo, di cinque membri, con ministri
responsali; elettivi sono pure i magistrati giudiziali; libera la stampa,
ma vietate le società popolari; espulsi per sempre quei ch’erano
fuorusciti; sanzionata la vendita dei beni nazionali; liberi i culti, nè
stipendiati dal Governo.
Raffazzonata così la civile convivenza, il Direttorio sconnette la
coalizione nemica facendo pace con Prussia e Spagna; e poichè la
principale sua avversatrice era l’Austria, pensò portarle guerra in
Germania non meno che in Italia. E qui comincia l’età omerica della
rivoluzione, colle grandi conquiste che le erano necessarie per farsi
riconoscere e per diffondere le idee e i sentimenti suoi. Il generale
Scherer ingrossato sulle Alpi, con Massena e Serrurier batte Devins
e Colli (22-28 9bre), in una serie di fatti che denominaronsi la
battaglia di Loano, prendendone tutta l’artiglieria ed il carreggio: i
vinti precipitandosi in fuga, non meno che i vincitori stuprando e
devastando, lasciarono tutta la Liguria esposta ai Francesi; onde se
Scherer allora drizzava sopra Torino, non trovava ostacolo: ma ebbe
paura dell’inverno; poi non finiva di rimostrare i bisogni d’un esercito
che lasciavasi mancante di tutto; e non vedendosi ascoltato, mandò
la dimissione, e fu surrogato da Napoleone Buonaparte (1796 23
febb.).
Discendeva questo da un Guglielmo di Pistoja, che nelle guerre del
Quattrocento si stabilì a Sarzana, donde Francesco nel 1530
tramutò la famiglia in Corsica. Ivi i Buonaparte coi Saliceti
parteggiavano per Francia; onde al sormontare del Paoli e dei
Pozzodiborgo andarono proscritti. Ricoverati a Marsiglia, madama
Letizia rimasta vedova, vivea dimessamente; le avvenenti sue
figliuole facevano i servigi della casa; i molti maschi correano le
fortune di quel tempo, e tra essi Napoleone, nato il 5 agosto 1769,
educato dallo zio prete, scriveva in sentimento giacobino, firmandosi
Bruto Buonaparte. Entrato nell’esercito, lo trovammo in Sardegna,
poi alla difesa di Tolone come artigliere, poi a sedare
sanguinosamente le insurrezioni in Parigi. Ora spedito sopra l’Italia,
di cui le barriere in ogni parte già erano superate, prometteva, — Fra
tre mesi sarò reduce a Parigi, o vincitore a Milano».
Al crescere del pericolo, l’Austria mandò sull’Alpi Beaulieu, generale
esercitato sotto il maresciallo Daun, poi segnalatosi nel Brabante e a
Fleurus e nel liberare Magonza dai Francesi, e che alla sperienza di
vecchio univa spiriti giovanili. Ma non guidava più di trentaduemila
soldati, oltre mille ducento cavalli napoletani; e la gelosia toglieva
che gli alleati operassero d’accordo. I quali, mentre vantavano
tutelare i troni e la società, ruminavano parziali ambizioni; il
Piemonte sperava guadagnare la Lombardia a scapito dell’Austria
sua alleata, dalla quale non volea lasciar occupare le fortezze;
l’Austria di rimpatto sperava ciuffare il Veneto, e ricuperare la
Lomellina e il Novarese, sicchè parve poco curare i disastri del
Piemonte, persuasa a vicenda che a questo non rincrescerebbe
vederla espulsa dal Milanese dov’è destinato a succederle. Il
Direttorio dava dunque incarico a Buonaparte di rincacciare gli
Austriaci oltre il Po, sicchè i Piemontesi isolati dovessero piegare a
buoni accordi.
Buonaparte, moderato nell’ardimento, vedea bisognare altro sistema
che le campagne metodiche; e che, colpita l’Austria, ai principotti
italiani nulla resterebbe a fare; ma insieme che bisognava smettere
la propaganda sovvertitrice; e «se noi (pensava) colla libertà
attizziamo la guerra civile in Piemonte e a Genova, e solleviamo le
plebi contro i nobili e i preti, ci facciamo rei degli eccessi di tali lotte.
Sull’Adige invece possiamo eccitare il patriotismo contro lo straniero,
senza nimicare le classi, le quali tutte alla parola Italia Italia, bandita
non dal Ticino, ma da Milano o da Bologna, si accorderanno a
ristabilire la patria italiana».
A Nizza (20 marzo) egli trovò trentaseimila Francesi in condizione
deplorabile; non vesti, non denaro, non cavalli, non viveri; ma
coraggio, costanza, impeto repubblicano e bravi capitani, quali
Massena senza paura, Augereau spadaccino che trasfondeva il
proprio valore ai soldati, il coraggioso ed istrutto svizzero Laharpe, il
prode e metodico Serrurier, Berthier eminente nelle particolarità e
nel colpo d’occhio, e Miollis, Lannes, Murat, Junot, Marmont,
destinati a vivere nella storia quanto gli eroi di Grecia e Roma. Fra
loro Buonaparte, smettendo le famigliarità repubblicane, si dà aria di
capo benchè sia il più giovane; ai generali distribuisce quattro luigi
per uno; ai soldati dice: — Voi male vestiti, male pasciuti; e il
Governo che tutto vi deve, nulla può per voi. Io vi condurrò nel
paradiso terrestre, dove piani ubertosi, grandi città, laute provincie;
dove troverete onore, gloria, ricchezze».
Mentre Beaulieu aspettava d’essere attaccato per Genova, egli
procede per la valle della Bormida; e vincitore la prima volta a
Montenotte, poi al passo di Millesimo (11-14 aprile), sapendo
profittare di quei quarti d’ora che decidono delle battaglie, sbocca
sovra il centro nemico, separa gli Austriaci dai Piemontesi, avventasi
sopra questi, e da Cherasco proclama: — Italiani, l’esercito di
Francia viene a frangere le vostre catene; il popolo francese è amico
di tutti i popoli; corretegli incontro; le proprietà, le usanze, la religione
vostra saranno rispettate. Faremo la guerra da nemici generosi, e
solo coi tiranni che vi tengono servi»; e vincitore a Ceva, Mondovì,
difila sopra Torino.
Il re di Sardegna, inquieto anche per le turbolenze sarde (28 aprile),
impetra un armistizio: ma tale debolezza, non che salvarlo, mette il
suo paese al pieno arbitrio dei nemici, ai quali se avesse tenuto
testa, poteva cambiare il corso delle vicende italiche. E nobili e Corte
diedero il primo pascolo di adulazioni servili al giovane prode: il
quale impose di cedere la Savoja, Nizza e le fortezze di Ceva,
Cuneo, Alessandria, Tortona, strada fornita tra Francia e Lombardia;
altre smantellarne; amnistia ai repubblicanti; pagar taglie e viveri pei
soldati. La Brunetta, con tant’arte e tesori resa insuperabile chiave
d’Italia, fu sfasciata senza ostacolo.
Buonaparte, con esercito pasciuto, coll’artiglieria acquistata, con
volontarj accorsi, «riportate (com’egli diceva) sei vittorie in quindici
giorni, presi ventisei vessilli, cinquantacinque cannoni, molte piazze,
quindicimila prigionieri, guadagnato battaglie senz’artiglieria, passato
fiumi senza ponti, marciato senza scarpe, serenato senz’acquavite e
talora senza pane» [10], per la destra del Po cala verso Lombardia, in
pingui convalli, sopra terreno proporzionato alla forza dell’esercito.
Entrato sugli Stati di Parma e Piacenza, che sotto i Borboni si erano
ristaurati dalle guerre e fiorivano d’agricoltura, arti, commercio,
concede al duca armistizio per due milioni di lire, milleseicento
cavalli e grano, oltre venti quadri dei migliori. E mentre i Tedeschi
l’attendono dritto a Valenza, egli obliquamente passa il Po a
Piacenza, batte Beaulieu tardi accorso (9 maggio), a Lodi varca
sanguinosamente l’Adda (11 maggio), e arriva a Milano, donde
l’arciduca era partito senza resistenza nè compianti, ma con
grand’accompagnamento di persone, che dai repubblicani si
salvavano sul territorio veneto. Ivi pure rifugge Beaulieu colle truppe
austriache, sol tenendo Mantova; poichè il castello di Milano capitolò
(29 giugno), e i disertori e migrati che v’erano furono consegnati al
generale francese.
Egli, prendendo possesso della Lombardia, bandiva che «ognuno
dovesse contribuire al bene generale; goder sicuro delle sue
proprietà; esercitare i proprj diritti sotto la scorta della virtù;
riconoscendo un Dio, praticando il culto che la sua coscienza
gl’ispira; non altra distinzione fra gli uomini che il merito; si
ricordassero che verun’opera riesce perfetta di primo getto, e i
grandi errori si riparano colle virtù e colla moderazione». Lascia
armare le guardie nazionali, fare grandi allegrezze, prevalere quelli
ch’erano già capi nelle loggie massoniche, stabilire ritrovi politici e
gazzette declamatorie; e tutt’insieme gitta venti milioni per tassa di
guerra, cioè il quintuplo di quanto pagavasi in un anno ai tiranni
espulsi, e non equamente ripartiti sul censo, ma riscossi
arbitrariamente sopra gl’individui. In nome della libertà fece
deportare i sessanta membri dell’antica congregazione di Stato; in
nome della democrazia rapiva al povero il suo pane, cioè i pegni che
aveva deposti ne’ Monti di pietà, e il suo lusso, cioè gli ornamenti
delle chiese; tra i vanti di fede pubblica sospendeva i pagamenti del
Monte; tra i vanti di protezione rubava i capi d’arte, mascherando
d’entusiasmo i calcoli dell’egoismo.
Per dieci altri milioni e viveri e quadri concede armistizio ad Ercole III
duca di Modena, buon uomo che, per ammansarlo, aveagli detto, —
Ricordatevi che siete de’ nostri» e si udì rispondere, — Io son
francese»; e che coi tesori adunati pagando i danni dei sudditi ai
quali avea cercato far del bene, si ritirò a Venezia [11].
Buonaparte, alimentato l’esercito, può spedire al bisognoso
Direttorio trenta milioni e cento cavalli di lusso, ed altro denaro
all’esercito del Reno; atto inusitatissimo fra generali che solo
pensavano a rubare e godere. Era suo divisamento di voltare nel
Tirolo, e per la valle del Danubio ricongiungersi a Moreau e Jourdan
sul Reno: ma il Direttorio ingelositone lo dichiarò chimerico e
pericoloso, e ordinogli di lasciare mezzo l’esercito con Kellermann in
Lombardia, col resto difilarsi sopra Roma e Napoli. Buonaparte che
badava a vincere non a fare dispetti al papa o a un re, conobbe
quanto pregiudicherebbe lo spartire il comando e addentrarsi
nell’Italia come Carlo VIII; e per mezzo di Giuseppina, amante sua e
dapprima amante del direttore Barras trafficante di favori, a
disposizione del quale egli mise un milione depositato a Genova,
stornò il Direttorio da quel proposito. Al quale scriveva: — Ho fatto la
campagna senza consultare nessuno; a nulla di buono sarei riuscito
se fosse bisognato acconciarmi col vedere d’un altro. Vinsi forze
superiori sebben privo di tutto, perchè persuaso che voi fidavate in
me: la mia marcia fu pronta quanto il mio pensiero. Se mi ponete
pastoje, non v’aspettate nulla di buono: se mi indebolite dividendo le
mie forze, se rompete in Italia l’unità del pensiero militare, avete
perduto la più bella occasione d’imporre leggi all’Italia».
Allora egli si dispose ad assediare Mantova, ultimo ricovero della
bandiera austriaca, e procedere su per l’Adige. Enumerati
pomposamente i trionfi all’esercito, diceva: — Altre marcie forzate ci
restano, nemici a sottomettere, allori a cogliere, ingiurie a vendicare.
Quei che aguzzarono i pugnali della guerra civile in Francia, tremino:
i popoli stieno sicuri; noi siamo amici de’ popoli. Ristabilire il
Campidoglio, risuscitare il popolo romano da molti secoli di schiavitù,
sarà frutto delle nostre vittorie. Il popolo francese, libero, rispettato
da tutti, darà all’Europa una pace gloriosa che la compenserà de’
seienni sagrifizj. Voi tornerete allora ai vostri focolari, e i concittadini
additandovi diranno, Egli era nell’esercito d’Italia».
Il pericoloso entusiasmo per la forza fortunata, allora fa eccheggiare
dei vanti dell’eroe la Francia, che divezzandosi dall’anarchia,
all’ebrezza della libertà va sostituendo quella della gloria; e l’Italia,
sospesa fra ansietà, meraviglia e speranza. Egli a ventott’anni
carezzato, adulato, chiamato Scipione, Cesare, Giove, sentì
svilupparsi la grande ambizione, e conobbe di poter divenire un
attore decisivo nella scena politica. — Io era giovane, balioso nella
conoscenza di mie forze e avido di cimentarle. I vecchi mustacchi
che sdegnavano questo imberbe comandante, ammutolirono davanti
alle mie azioni strepitose: severa condotta, austeri principj pareano
strani in un figlio della Rivoluzione. Io passava, e l’aria sonava
d’applausi; tutto pendeva da me, dotti, ignoranti, ricchi, poveri,
magistrati, clero, tutto ai miei piedi; il nome mio sonava caro
agl’Italiani. Questo accordo d’omaggi mi invase così, che divenni
insensibile a ciò che non fosse gloria; invano le belle italiane faceano
pompa de’ loro vezzi; io non vedea che la posterità e la storia. Che
tempi! che felicità! che gloria!»
Così, allorchè a Sant’Elena soccombeva al peso di importune
memorie, tornava Buonaparte con compiacenza su questa
spedizione, ch’è uno splendido episodio per tutta Europa, e una
storia delle più attraenti per noi; vi tornava, e con rimorso invano
dissimulato vedeva il bene che avrebbe potuto fare alla patria nostra;
egli italiano come noi, egli braccio d’un popolo libero; egli capace di
sentire la potenza dell’unione e l’efficacia dell’ordinata libertà: pure,
dopo cessati gli adulatori, egli si adulava da sè, e, come quelli,
arrestavasi sempre sulla gloria militare.
Dalla quale affascinati, i colti Lombardi che aveano letto gli
Enciclopedisti poi le gazzette, partecipato a loggie massoniche,
librato le innovazioni dei proprj principi, da lui ripromettevansi patria,
gloria, libertà, e di diventare nucleo dell’Italia, risorta in poderosa
nazione per volontà d’un popolo libero e liberatore. La turba stupiva
delle subitanee vittorie dell’eroe italiano, e abbandonavasi volentieri
al tripudio del fanciullo che improvvisamente si trova sfasciato, e alle
illusioni d’un fausto avvenire; si affezionava a que’ Polacchi che,
invano difesa la nazionale libertà, ora combatteano per la nostra; a
quei Francesi vivaci, gentili, spassoni, che da lerci e cenciosi rimessi
in panni e in carne, faceansi amare dagli uomini e più dalle donne,
brillavano in frequenti rassegne, narravano le romanzesche vicende
della rivoluzione e della guerra, e le stranianze d’una società che
ridendo passò dalle cene voluttuose della Reggenza alla ghigliottina,
dagl’idillj di Rousseau alla idrofobia di Marat; e colle canzoni
sanguinarie e generose spargeano le idee d’una libertà soldatesca.
Dappertutto agli antichi Governi si sostituirono le municipalità, primo
elemento delle nazioni che sorgono, ultimo rifugio dell’autorità che
tramonta. A principio vi si collocarono persone, di cui il senno, la
ricchezza, la dottrina fossero garanzia d’onorato operare, e fra essi a
Milano Pietro Verri e Giuseppe Parini. Ma furono bentosto
soppiantati dalla turba impacciosa, ch’è pronta sempre ad
usufruttare di vittorie ch’essa non preparò, e che si regge adulando
la ciurma colle smargiassate, adulando gli scribacchianti colle parole
pompose, adulando i padroni colla codardia e i ladri colla
connivenza.
Anche allora il primo uso della libertà consistette nel restringere le
libertà; vietato l’andare in volta, e fin l’uscire di città senza
passaporti; vietata ogni pubblicità di culto, anche il portare il viatico o
sonare le campane; obbligati i preti a montare la guardia nazionale;
vietati certi tagli d’abiti, sotto pena dell’arresto; il matrimonio fatto
meramente atto civile; violato il secreto delle lettere; intercetti i
giornali esteri; imposto agl’impiegati di giurare «odio eterno al
governo dei re, degli aristocratici ed oligarchi». I nobili, in paese
dove non esistevano nè servaggio nè banalità nè caccie riservate,
erano bersaglio di scherni e di accuse quotidiane; e non che abolirne
i titoli e spezzarne gl’inconcludenti stemmi fin sui sepolcri aviti, si
obbligarono a pesi speciali in nome dell’eguaglianza; richiamati dalla
campagna, costretti a tenere i servi, malgrado le decimate fortune. I
preti, che non vollero buttarsi nell’orgia, nè menare una donna
all’albero per isposarla, doveano subire frequenti insulti in mezzo alla
popolazione che continuava a venerarli, ma non aveva energia a
difenderli.
Adunque preti, frati, nobili e l’estesissima loro clientela sbigottivano
delle irruenti novità, spargeano un cupo sgomento pei regicidi, pei
terroristi, pei sovvertitori dei troni e della fede; e quando si videro le
larghe promesse riuscire al latrocinio, alle insaziabili imposte, allo
sprezzo della religione e delle consuetudini, il popolo fremette e si
agitò.
Pavia era occupata da Augereau e Rusca, tutt’altro che moderati, i
quali pronunziarono stava male in faccia all’albero della libertà la
statua d’un tiranno; tale giudicando quel monumento di bronzo
antico, detto il Regisole che non si sa qual cosa rappresenti. E subito
la plebe gli fu attorno a ruinarlo, urlando morte agli aristocratici e ai
preti. Questi invece pascolavansi della speranza che l’occupazione
fosse momentanea, e ad un giorno fisso insorgerebbe Milano (23
maggio), e dal Ticino tornerebbero i Tedeschi. Due soldati prigionieri
fuggiti si credettero l’avanguardia; si diè nell’armi; le campane delle
ventotto chiese toccarono a martello, e barricate, e lumi; i soldati che
non cadono uccisi hanno appena tempo di ricoverare nel castello,
ove non avendo da vivere e da curare i feriti, capitolano in numero di
quattrocento. Pensate che feste, che trionfi, che accorrere di popolo
dalla campagna, che trescare di capitani improvvisati! Ma
Buonaparte saputone, accorre; manda a fuoco e sacco Binasco che
resiste; e poichè a Pavia spedì invano l’arcivescovo di Milano
persuasor di pace, v’entrò a forza e abbandonolla al saccheggio.
Molti perirono, fra cui il vicario d’esso arcivescovo; e Buonaparte
giurava di volere la testa di cento aristocratici; poi s’accontentò di far
passare per l’armi il curato di San Perone, il cancelliere di
Bereguardo e alcuni altri, colpevoli o no; portare ostaggi sessanta fra
nobili e preti; gettare una tassa; contento di atterrire coll’esempio in
su quelle prime [12].
Anche altrove il popolo, sturbato nelle sue abitudini, offeso nelle sue
credenze, si stomacava a subbugli di cui non sentiva i vantaggi, e di
cui vedeva profittare soltanto i birbi e i trasmodanti. Quindi in molti
luoghi insurrezioni: sul lago di Como si stringeva un’armata cattolica
per scortare il Viatico e difendere il culto: a Como s’insultò all’albero,
e benchè il vescovo e buoni cittadini calmassero l’improvvida turba,
si volle sbigottirla con supplizj; così altrove, usando la ferocia d’un
governo militare, mentre se ne facea testo a declamare contro i preti
e gli aristocratici, imputati al solito di congiure. Saliceti, compatrioto
di Buonaparte e famoso commissario, che dava mano agli esagerati,
teneva mano ai ladri, scriveva al Direttorio: — Per assicurare la
calma ho tolto le armi a qualunque abitante, di nessuno essendo a
fidarsi. Da un ventesimo in fuori tutti affezionano l’antico Governo; e
di quel ventesimo anche i più dichiarati pe’ Francesi sono spinti da
interesse e cupidigia. Li conosco, ne cavo quanto posso, e non mi
lascio togliere la mano».
Allora una febbre di mutare mestiere; un cattivo abate si rendeva
politico, finanziere un filologo, oratore demagogo uno screditato
giornalista, arruffatore di plebi un adulatore di re, libellista un serio
filosofo inascoltato; alla democrazia, che schiude un’arena a tutte le
forze e capacità, sottentrava quella che porta a spallucce i nani, che
produce apoteosi senza virtù, avanzamenti senza merito, cariche
senza cognizione nè probità; che alla moderatezza, alla riflessione,
alla gravità, necessarj contrappesi dello smanioso moto, impongono
di tacere e tirarsi da banda. Audacia, ciancie e convulsioni
bastavano ai saccenti che vengono a galla ogniqualvolta si scuota la
feccia, più abbondanti ov’è più negletta la politica educazione, e che
per l’ingordigia d’essere qualcosa affollano mozioni e decreti,
antesignani ogniqualvolta si tratta di diletticare i potenti del giorno,
siano i re o i piazzajuoli, purchè lascino loro una settimana onde
soddisfare un’ambizione, un rancore, una cupidigia. Il vulgo
scribacchiante che pretende avere diretto il torrente, da cui si lasciò
strascinare, e crede sue le voci di cui non è che l’eco, arrogavasi di
rappresentare il popolo e l’opinione, gridando alto affinchè non
s’udissero le ragioni. Quella bordaglia giornalistica, che ogni
cominciamento di libera stampa contamina quasi col proposito di
farla detestare, imbrattava fogli, tutti iracondia, fraterni vituperj ed
empie diatribe, istigando contro chi non partecipasse al suo delirio, o
non ne accettasse servilmente tutte le opinioni; scaraventava
proclami, in cui la sola cosa degna di considerazione è il vederli,
sentimenti e frasi, ripetuti in pari circostanze un mezzo secolo più
tardi. Apostolavano un sistema di cui non comprendevano le
obbligazioni; destri alle schermaglie della rivoluzione, non alle
battaglie della libertà, usavano talento ov’era mestieri di carattere; e
coll’audace franchezza onde aveano rovesciate le prime barriere,
sfrenavansi da principj e da costumi, in libertà di oltraggio se non
anche di delitto.
Quanto di più fermentativo aveano le varie provincie d’Italia,
accorreva a Milano, portando lingue e penne anzichè braccia e
spade: ivi il metafisico Poli e lo statistico Melchior Gioja, più
esagerando per farsi perdonare l’unzione sacerdotale; il Valeriani,
autore dell’esame delle XII Tavole; il valente medico Rasori; il
Barbieri architetto romano; l’erudito Tambroni, lo storico Beccatini, il
Custodi economista; ivi Latanzio, Salvadori, Salfi, Poggi, Abamonti
stendeano giornali smargiassi, con lusso d’ingiurie e col limaccioso
vezzo di voltare tutto in celia; ivi Ceroni, Fantoni, Foscolo
producevano versi accademicamente rivoluzionarj; ivi il romano
Gianni [13] improvvisava vituperj ai re ed apoteosi a Buonaparte,
incontrastato Tirteo della Cisalpina, finchè non vi capitò il Monti a
redimersi delle esagerazioni papali con esagerazioni regicide. Il
fermento ne cresceva, e tanto più dacchè, a imitazione sempre di
Francia, si apersero i club e il circolo Patriotico, ove persone, balzate
dalla venerazione illimitata del potere all’idolatria dell’illimitata libertà
individuale, gareggiavano a chi ne scaraventasse di più badiali,
pindareggiando un eroismo scevro di pericolo: non v’era persona,
non cosa che si rispettasse, non violenza che non si suggerisse o
applaudisse, non verità che si tollerasse; bruciando i libri che
opinassero diversamente dalla moda, o i giornali che dessero notizie
non volute; tacciando di terrorista chi avvisasse de’ pericoli, e intanto
supponendo pericoli immaginarj per giustificare provvedimenti
smoderati. Da quei circoli partivano le proposizioni di non far
assistere da preti i condannati per non allungare il supplizio;
d’imporre la tassa progressiva sulle sostanze; d’istituire opifizj
nazionali, e accomunare le proprietà; da quelli i sospetti lanciati al
popolo in momenti in cui facilmente si convertono in furori; da quelli
le denunzie contro vescovi che aveano visitato la loro diocesi senza
permesso, o parrochi che aveano fatto una festa: tutto ciò in nome
della libertà ed uguaglianza. Altri smaniavano d’originalità con
proposte ridicole al buon senso, col guidare feste, organizzare
dimostrazioni: fra i quali primeggiò un prete Ranza, maestro
d’umanità a Vercelli, le cui smancerie divennero la parte comica di
quegli avvenimenti e l’esercizio alle descrizioni del Botta.
Polacchi, Piemontesi, Papalini, Napolitani migrati vi portavano
ciascuno declamazioni contro il tiranno del proprio paese; e quale
esortava a far rinascere dalle ceneri del Vaticano la fenice dell’antica
Roma; quale a sepellire nel Vesuvio i Borboni di Napoli; quale a
sperdere le ceneri regali di Superga, e surrogarvi quelle de’ patrioti
uccisi; tutti smisurati come chi parla e non opera. Le dottrine
indecise di que’ declamatori palesano l’ignoranza delle grandi
quistioni messe a dibattimento, ove la sapienza accumulata da’
nostri padri in diciotto secoli si vituperava per razzolare nelle ceneri
di Bruto e Timoleone; vedeansi Regoli e Scevola e Scipj e Menenj
Agrippa in ogni caporale, in ogni magistrato: in ogni donna
prometteansi Clelie e Cornelie. Eppure tutto quel lancio era pretta
imitazione; non si sapea che ripetere le massime divulgate in
Francia; ogni re essere tiranno; puntelli suoi i preti e i nobili; sovrano
unico il popolo, che può in qualsiasi tempo e modo recuperare gli
usurpatigli diritti; unico Governo legittimo la repubblica democratica;
unica fedeltà quella al popolo, e lode il tradire i principi; nessun
intermedio fra l’uomo e Dio, e perciò non dogmi, non culto; tutti pari
davanti alla legge, e la legge è arbitra delle vite e delle sostanze,
come dominatrice del patto sociale. Dietro a ciò, fare elegie sul
popolo, compatire come martire ogni uomo colpito dalla legge, come
vittima chiunque fosse gravato da una tassa, o traversato in un suo
desiderio; vedere oppressione in ogni ritegno alle inclinazioni, in ogni
sacrifizio del comodo o dell’utile individuale al pubblico; iniquità in
ogni disuguaglianza, despotismo in ogni autorità.
Fortunatamente v’era più da ridere che da fremere, più illusione negli
spiriti, che non viltà e corruzione ne’ cuori: nè degli errori possiamo
chiedere conto rigoroso ai nostri, giacchè non erano che stromenti
ed ombre degli onnipotenti governatori militari. Un Despinoy
comandante di piazza era il despoto di Milano: guai se la
municipalità si raccogliesse senza sua saputa! guai se un
provvedimento emanasse non da lui autenticato! Fu volta che snudò
la spada e la battè fieramente sulla tavola dove si deliberava,
intimando la sua volontà; sicchè il Parini abbrancando la sciarpa
tricolore che portava sul petto, — Chè non ce la cingete al collo e la
stringete?» A Como l’agente Valeri côrso, avuta in mano una satira a
sua derisione, ordina che un tal giorno tutti i cittadini in su dai dodici
anni si radunino in duomo. In tempi così sospettosi ne nacque un
turbamento generale, un interrogarsi a vicenda su quell’ordine
misterioso. Ed ecco arrivare i parrochi con dietro la loro plebe,
arrivare frati, e tutti in pensosa apprensione: poi come furono dentro,
egli ordinò che ciascuno scrivesse il proprio nome, sperando dal
confronto de’ caratteri scoprire l’autore di quel libello.
E ferocie e lepidezze molte potrei narrare di costoro; e i nostri
gl’imitavano. Un comitato di polizia, sostituendo l’arbitrio dell’uomo
all’imparzialità della legge, destituiva, deportava per colpe
d’opinione, per antichi meriti, per supposta malevolenza; pretendeva
mettere in onore lo spionaggio, e apriva un’urna, ove ciascuno
potesse deporre le accuse od offrirsi a delatore, sicuro d’una
ricompensa e d’inviolabile segreto [14].
Cangiata la frasca, restava dunque eguale il vino; al posto d’un
imperatore e d’un arciduca faceano da tiranno molti generali,
commissarj di guerra, municipalisti, più duri perchè nuovi, più avidi
perchè sorti di ventura, più tediosi perchè vicini. Peste di quella
spedizione, i commissarj di guerra dilapidavano le provincie per
impinguare sè e le bagascie; e dappertutto prezzi ad arte rincariti,
finte carestie, contratti finti, finti soldati, finti magazzini; si requisivano
tele per gli ospedali, e andavano in vendita; prometteasi preservare
da imposte chi pagasse, e pagato che avesse veniva disanguato;
della chinachina allora costosissima, faceasi traffico, mentre i soldati
morivano di febbre; e Italiani teneano il sacco, e la connivenza de’
superiori compravano a prezzo della coscienza, delle mogli, della
patria.
Buonaparte chiedeva, non già che costoro non rubassero, ma che,
rubando a sazietà, rendessero almeno i servigi necessarj: ma
«rubano (scriveva al Direttorio) in maniera così grottesca e sfacciata,
che non uno sfuggirebbe al supplizio s’io avessi un mese di tempo».
Per liberarsi da questi vampiri, i nostri offersero contribuire un
milione al mese alla repubblica francese: fu accettato il patto, non
cessò quella rabbia. Il Direttorio di Parigi faceva a mezzo, nè avea
riguardo che all’esercito; l’Italia era pingue, e bisognava smungervi
principi e repubblicanti; il Milanese sarebbe buono per dare in
cambio della Savoja al Piemonte o de’ Paesi Bassi all’imperatore,
dunque era bene rovinarlo sicchè men fruttuoso arrivasse a quelli; e
senza pudore scriveva a Buonaparte: — Alla prima occasione di
terrore, strizzate dai Lombardi quanto potete; fate di guastare anche
i loro canali e l’altre opere pubbliche; ma prudenza!» Buonaparte
guardavasi dal lasciarne trapelare, anzi blandiva le idee sempre
allettatrici di libertà e indipendenza, e ripeteasi amico a tutti i popoli,
e massime ai discendenti degli Scipioni e dei Bruti.
Intanto il contagio repubblicano s’appiglia a tutta Italia; e patrioti
come si chiamavano da sè, o giacobini come erano chiamati dagli
altri, scassinavano il vecchio edifizio. Ad esortazione di Buonaparte
che, se non altro aveva il merito di mostrare la colpa e il danno delle
nostre divisioni, deputati cisalpini andavano attorno a fraternizzare;
la media Italia bolliva d’indipendenza, e Reggio per la prima
mandava Paradisi e Re in Milano a festeggiare coi Cisalpini
l’incipiente unità italiana. Modena resistette ai patrioti; ma
Buonaparte, allegando violato l’armistizio e che «que’ ridicoli
principotti cospiravano, ond’egli dovea prevenirli», dichiara decaduto
quel duca e libero il suo paese. Bologna e Ferrara ergevansi in
repubblica; e Lugo che fece movimento contrario, ebbe sanguinosa
punizione da Augereau. Nella legione lombarda Italiani d’ogni paese
dimenticavano le annose divisioni; nella polacca i compagni di
Kosciusko e i profughi di Germania offrivano il loro valore per noi; i
Reggiani affrontandosi cogli Austriaci, offersero le primizie dell’italico
valore.
Buonaparte risolve costituire Modena, Bologna, Ferrara, la
Romagna, la marca d’Ancona e Parma in repubblica Cispadana; la
quale restasse alla Francia qualora dovesse restituire la Lombardia;
in compenso al duca di Parma darebbe Roma; potrebbesi anche
unire il Piemonte alla Francia, e attribuire a quel re la Lombardia:
soliti azzeccamenti della diplomazia sia regia o repubblicana.
Di rimpatto aristocratici, Austriaci, Inglesi, il papa faticavano a
puntellare il crollante edifizio con armi e con denaro. L’Austria,
sentendo che, se perdesse Mantova, si troverebbe scoperta da
questo lato, spedì pel Tirolo e la val Sugana il maresciallo Wurmser
(1796 luglio) con sessantamila combattenti. Secondati da diecimila
che trovavansi chiusi in quella fortezza, e dai devoti Tirolesi, erano
per varcare l’Adige in ogni punto, e prendere Buonaparte in mezzo;
onde cadde il cuore ai patrioti, risorse ai rammaricosi. Ma
Buonaparte osa abbandonare Mantova inchiodando le artiglierie (30
agosto), e concentrasi alla punta del lago di Garda: ben tosto colla
battaglia di Lonato rintegra la sua fortuna; poi a Castiglione compie
la campagna, sessantamila uomini avendo superati con trentatremila
e colla sua risolutezza.
In Germania il giovane arciduca Carlo spiegava più fortunata
strategia contro Jourdan e Moreau: e Buonaparte volea correre a
sostenerli; ma Wurmser, accinto a una terza riscossa, divallasi dal
Tirolo lungo il Brenta, e lo costringe a dare indietro. Qui si ravvivano
le speranze: ma Wurmser battuto a Bassano riuscì a fatica a buttarsi
in Mantova (8 7bre), ove rinnovato l’assedio, s’ebbe a soffrire orribile
stretta di vittovaglie.
L’Austria, a cui nessuno sforzo parve mai eccessivo per conservare
la Lombardia, manda ancora il maresciallo Alvinzy; e questo
rinnovellarsi di lotte scoraggia i soldati, non Buonaparte. Vedendo
minacciata la linea dell’Adige, gli uffiziali persuadevano di tagliare la
costa di Castagnaro, sicchè il fiume, disalveando, sarebbesi misto
col Tartaro e colla fossa d’Ostiglia, allagando quant’è fra l’Adige, il
mare e il Po sotto Legnago, e con ciò assicurando l’ala destra ed
accorciando la linea militare: ma Buonaparte non volle quel guasto.
Dopo fiere battaglie attorno ad Arcole (15 novembre) e a Rivoli (16
gennajo 1797), gli Austriaci furono costretti ancora a ritirarsi a
Mantova e capitolare (1797 2 febb.), così assicurata l’Italia superiore
alla Francia, dopo dieci mesi di mirabili operazioni.
Ma non soltanto come gran guerriero va lodato Buonaparte. Misto
portentoso di mobilità e profondità, di audacia e di previdenza, di
calcolo e d’entusiasmo, ardito ne’ concetti, prudente nell’esecuzione,
affettava ancora il tono di rivoluzionario, e al direttore Röderer
scriveva, — Sono un soldato, figlio della rivoluzione, uscito dal
popolo, e non soffrirò d’essere insultato come un re»; ma in effetto
aspirava a comporre e riordinare; rubava meno degli altri, sebbene
accettasse regali per sè, per la donna, pei parenti, e di continuo
inviasse denaro alla sua famiglia per educare i fratelli, per dotare le
sorelle, per procacciarsi una casa ove riposare se le vicende d’allora
lo riducessero ancora al nulla [15]; e sentendosi forte in mezzo ai
mediocri, operava senza ed anche contra le istruzioni del Direttorio,
concedeva pace e tregua a principi, rimbrottava i commissarj che
non facessero a suo modo, guadagnava quelli che, come Clarke,
fossero mandati ad esplorarlo.
Da un pezzo egli consigliava al Direttorio di far pace coi più forti Stati
d’Italia, e dichiarare l’indipendenza negli altri: di fatto un armistizio
egli concesse al re di Napoli (1796 10 8bre), onorevole perchè il
sapeva bene armato, ma a patto richiamasse i sussidj forniti
all’Inghilterra e all’Austria, aprisse i porti alle navi repubblicane,
desse sei milioni per Francia, la quale non favorirebbe l’insurrezione
nel paese: dei tanti prigioni di Stato non fece parola.
Morto di colpo Vittorio Amedeo III, che avea messo sua gloria nelle
armi, e n’era riuscito povero, vinto, disonorato, Carlo Emanuele IV
succedutogli (1796 15 8bre), di santi costumi, di malotica salute e
d’immaginazione turbata, comprò l’amicizia di Francia cedendole la
Savoja e Nizza, e liberi i passi. Quest’amicizia metteva in pericolo
Genova. Ad essa Buonaparte imponeva di frenare i Barbetti che

You might also like