Beginning Data Science in R: Data Analysis, Visualization, and Modelling for the Data Scientist 1st Edition Thomas Mailund download
Beginning Data Science in R: Data Analysis, Visualization, and Modelling for the Data Scientist 1st Edition Thomas Mailund download
https://textbookfull.com/product/beginning-data-science-in-r-
data-analysis-visualization-and-modelling-for-the-data-
scientist-1st-edition-thomas-mailund/
https://textbookfull.com/product/metaprogramming-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/
https://textbookfull.com/product/advanced-object-oriented-
programming-in-r-statistical-programming-for-data-science-
analysis-and-finance-1st-edition-thomas-mailund/
https://textbookfull.com/product/functional-data-structures-in-r-
advanced-statistical-programming-in-r-thomas-mailund/
Biota Grow 2C gather 2C cook Loucas
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/
https://textbookfull.com/product/practical-data-science-cookbook-
data-pre-processing-analysis-and-visualization-using-r-and-
python-prabhanjan-tattar/
https://textbookfull.com/product/functional-data-structures-in-r-
advanced-statistical-programming-in-r-mailund/
https://textbookfull.com/product/computer-science-in-sport-
modeling-simulation-data-analysis-and-visualization-of-sports-
related-data-2024th-edition-daniel-memmert/
https://textbookfull.com/product/a-data-scientist-s-guide-to-
acquiring-cleaning-and-managing-data-in-r-1st-edition-samuel-e-
buttrey/
Beginning
Data Science in R
Data Analysis, Visualization, and
Modelling for the Data Scientist
—
Thomas Mailund
Beginning Data
Science in R
Data Analysis, Visualization,
and Modelling for the Data Scientist
Thomas Mailund
Beginning Data Science in R: Data Analysis, Visualization, and Modelling for the Data Scientist
Thomas Mailund
Aarhus, Denmark
ISBN-13 (pbk): 978-1-4842-2670-4 ISBN-13 (electronic): 978-1-4842-2671-1
DOI 10.1007/978-1-4842-2671-1
Library of Congress Control Number: 2017934529
Copyright © 2017 by Thomas Mailund
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material
contained herein.
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Technical Reviewer: Andrew Moskowitz
Coordinating Editor: Mark Powers
Copy Editor: Kezia Endsley
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover image designed by Freepik
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance, Inc (SSBM Finance, Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/rights-
permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484226704. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Contents at a Glance
■
■Chapter 1: Introduction to R Programming����������������������������������������������������������� 1
■
■Chapter 2: Reproducible Analysis����������������������������������������������������������������������� 29
■
■Chapter 3: Data Manipulation������������������������������������������������������������������������������ 45
■
■Chapter 4: Visualizing Data��������������������������������������������������������������������������������� 75
■
■Chapter 5: Working with Large Datasets����������������������������������������������������������� 113
■
■Chapter 6: Supervised Learning������������������������������������������������������������������������ 125
■
■Chapter 7: Unsupervised Learning�������������������������������������������������������������������� 169
■
■Chapter 8: More R Programming����������������������������������������������������������������������� 205
■
■Chapter 9: Advanced R Programming��������������������������������������������������������������� 233
■
■Chapter 10: Object Oriented Programming������������������������������������������������������� 257
■
■Chapter 11: Building an R Package������������������������������������������������������������������� 269
■
■Chapter 12: Testing and Package Checking������������������������������������������������������ 281
■
■Chapter 13: Version Control������������������������������������������������������������������������������ 287
■
■Chapter 14: Profiling and Optimizing���������������������������������������������������������������� 303
Index��������������������������������������������������������������������������������������������������������������������� 347
iii
Contents
■
■Chapter 1: Introduction to R Programming����������������������������������������������������������� 1
Basic Interaction with R��������������������������������������������������������������������������������������������������� 1
Using R as a Calculator���������������������������������������������������������������������������������������������������� 3
Simple Expressions�������������������������������������������������������������������������������������������������������������������������������� 3
Assignments������������������������������������������������������������������������������������������������������������������������������������������� 5
Actually, All of the Above Are Vectors of Values…���������������������������������������������������������������������������������� 5
Indexing Vectors������������������������������������������������������������������������������������������������������������������������������������� 6
Vectorized Expressions��������������������������������������������������������������������������������������������������������������������������� 7
Comments������������������������������������������������������������������������������������������������������������������������ 8
Functions�������������������������������������������������������������������������������������������������������������������������� 8
Getting Documentation for Functions����������������������������������������������������������������������������������������������������� 9
Writing Your Own Functions����������������������������������������������������������������������������������������������������������������� 10
Vectorized Expressions and Functions������������������������������������������������������������������������������������������������� 12
v
■ Contents
■
■Chapter 2: Reproducible Analysis����������������������������������������������������������������������� 29
Literate Programming and Integration of Workflow and Documentation����������������������� 30
Creating an R Markdown/knitr Document in RStudio���������������������������������������������������� 30
The YAML Language������������������������������������������������������������������������������������������������������� 33
The Markdown Language����������������������������������������������������������������������������������������������� 34
Formatting Text������������������������������������������������������������������������������������������������������������������������������������� 35
Cross-Referencing�������������������������������������������������������������������������������������������������������������������������������� 38
Bibliographies��������������������������������������������������������������������������������������������������������������������������������������� 39
Controlling the Output (Templates/Stylesheets)����������������������������������������������������������������������������������� 39
Exercises������������������������������������������������������������������������������������������������������������������������ 44
Create an R Markdown Document�������������������������������������������������������������������������������������������������������� 44
Produce Different Output���������������������������������������������������������������������������������������������������������������������� 44
Add Caching����������������������������������������������������������������������������������������������������������������������������������������� 44
vi
■ Contents
■
■Chapter 3: Data Manipulation������������������������������������������������������������������������������ 45
Data Already in R������������������������������������������������������������������������������������������������������������ 45
Quickly Reviewing Data�������������������������������������������������������������������������������������������������� 47
Reading Data������������������������������������������������������������������������������������������������������������������ 48
Examples of Reading and Formatting Datasets������������������������������������������������������������� 49
Breast Cancer Dataset�������������������������������������������������������������������������������������������������������������������������� 49
Boston Housing Dataset����������������������������������������������������������������������������������������������������������������������� 55
The readr Package�������������������������������������������������������������������������������������������������������������������������������� 56
Manipulating Data with dplyr����������������������������������������������������������������������������������������� 58
Some Useful dplyr Functions���������������������������������������������������������������������������������������������������������������� 59
Breast Cancer Data Manipulation��������������������������������������������������������������������������������������������������������� 65
■
■Chapter 4: Visualizing Data��������������������������������������������������������������������������������� 75
Basic Graphics��������������������������������������������������������������������������������������������������������������� 75
The Grammar of Graphics and the ggplot2 Package������������������������������������������������������ 83
Using qplot()����������������������������������������������������������������������������������������������������������������������������������������� 84
Using Geometries��������������������������������������������������������������������������������������������������������������������������������� 88
Facets��������������������������������������������������������������������������������������������������������������������������������������������������� 97
Scaling������������������������������������������������������������������������������������������������������������������������������������������������ 100
Themes and Other Graphics Transformations������������������������������������������������������������������������������������ 105
vii
■ Contents
■
■Chapter 5: Working with Large Datasets����������������������������������������������������������� 113
Subsample Your Data Before You Analyze the Full Dataset������������������������������������������ 113
Running Out of Memory During Analysis���������������������������������������������������������������������� 115
Too Large to Plot����������������������������������������������������������������������������������������������������������� 116
Too Slow to Analyze������������������������������������������������������������������������������������������������������ 120
Too Large to Load��������������������������������������������������������������������������������������������������������� 121
Exercises���������������������������������������������������������������������������������������������������������������������� 124
Subsampling��������������������������������������������������������������������������������������������������������������������������������������� 124
Hex and 2D Density Plots������������������������������������������������������������������������������������������������������������������� 124
■
■Chapter 6: Supervised Learning������������������������������������������������������������������������ 125
Machine Learning��������������������������������������������������������������������������������������������������������� 125
Supervised Learning���������������������������������������������������������������������������������������������������� 125
Regression versus Classification�������������������������������������������������������������������������������������������������������� 126
Inference versus Prediction���������������������������������������������������������������������������������������������������������������� 127
viii
■ Contents
■
■Chapter 7: Unsupervised Learning�������������������������������������������������������������������� 169
Dimensionality Reduction��������������������������������������������������������������������������������������������� 169
Principal Component Analysis������������������������������������������������������������������������������������������������������������ 169
Multidimensional Scaling������������������������������������������������������������������������������������������������������������������� 177
Clustering��������������������������������������������������������������������������������������������������������������������� 181
k-Means Clustering���������������������������������������������������������������������������������������������������������������������������� 182
Hierarchical Clustering����������������������������������������������������������������������������������������������������������������������� 188
ix
■ Contents
Exercises���������������������������������������������������������������������������������������������������������������������� 204
Exploring Other Formulas������������������������������������������������������������������������������������������������������������������� 204
Exploring Different Models����������������������������������������������������������������������������������������������������������������� 204
Analyzing Your Own Dataset��������������������������������������������������������������������������������������������������������������� 204
■
■Chapter 8: More R Programming����������������������������������������������������������������������� 205
Expressions������������������������������������������������������������������������������������������������������������������ 205
Arithmetic Expressions����������������������������������������������������������������������������������������������������������������������� 205
Boolean Expressions�������������������������������������������������������������������������������������������������������������������������� 206
Functions���������������������������������������������������������������������������������������������������������������������� 220
Named Arguments������������������������������������������������������������������������������������������������������������������������������ 221
Default Parameters����������������������������������������������������������������������������������������������������������������������������� 222
Return Values������������������������������������������������������������������������������������������������������������������������������������� 222
x
■ Contents
■
■Chapter 9: Advanced R Programming��������������������������������������������������������������� 233
Working with Vectors and Vectorizing Functions��������������������������������������������������������� 233
ifelse��������������������������������������������������������������������������������������������������������������������������������������������������� 235
Vectorizing Functions������������������������������������������������������������������������������������������������������������������������� 235
The apply Family�������������������������������������������������������������������������������������������������������������������������������� 237
xi
■ Contents
Exercises���������������������������������������������������������������������������������������������������������������������� 255
between���������������������������������������������������������������������������������������������������������������������������������������������� 255
apply_if����������������������������������������������������������������������������������������������������������������������������������������������� 255
power������������������������������������������������������������������������������������������������������������������������������������������������� 255
Row and Column Sums���������������������������������������������������������������������������������������������������������������������� 255
Factorial Again������������������������������������������������������������������������������������������������������������������������������������ 255
Function Composition������������������������������������������������������������������������������������������������������������������������� 256
■
■Chapter 10: Object Oriented Programming������������������������������������������������������� 257
Immutable Objects and Polymorphic Functions����������������������������������������������������������� 257
Data Structures������������������������������������������������������������������������������������������������������������ 257
Example: Bayesian Linear Model Fitting��������������������������������������������������������������������������������������������� 258
Classes������������������������������������������������������������������������������������������������������������������������� 259
Polymorphic Functions������������������������������������������������������������������������������������������������� 261
Defining Your Own Polymorphic Functions����������������������������������������������������������������������������������������� 262
Exercises���������������������������������������������������������������������������������������������������������������������� 267
Shapes������������������������������������������������������������������������������������������������������������������������������������������������ 267
Polynomials���������������������������������������������������������������������������������������������������������������������������������������� 267
■
■Chapter 11: Building an R Package������������������������������������������������������������������� 269
Creating an R Package������������������������������������������������������������������������������������������������� 269
Package Names���������������������������������������������������������������������������������������������������������������������������������� 269
The Structure of an R Package����������������������������������������������������������������������������������������������������������� 270
.Rbuildignore�������������������������������������������������������������������������������������������������������������������������������������� 270
Description����������������������������������������������������������������������������������������������������������������������������������������� 271
NAMESPACE���������������������������������������������������������������������������������������������������������������������������������������� 274
R/ and man/���������������������������������������������������������������������������������������������������������������������������������������� 275
xii
■ Contents
Roxygen������������������������������������������������������������������������������������������������������������������������ 275
Documenting Functions���������������������������������������������������������������������������������������������������������������������� 275
Import and Export������������������������������������������������������������������������������������������������������������������������������� 276
Package Scope Versus Global Scope�������������������������������������������������������������������������������������������������� 277
Internal Functions������������������������������������������������������������������������������������������������������������������������������� 277
File Load Order����������������������������������������������������������������������������������������������������������������������������������� 277
xiii
■ Contents
GitHub��������������������������������������������������������������������������������������������������������������������������� 297
Moving an Existing Repository to GitHub�������������������������������������������������������������������������������������������� 299
Installing Packages from GitHub�������������������������������������������������������������������������������������������������������� 300
Exercises���������������������������������������������������������������������������������������������������������������������� 301
■
■Chapter 14: Profiling and Optimizing���������������������������������������������������������������� 303
Profiling������������������������������������������������������������������������������������������������������������������������ 303
A Graph-Flow Algorithm��������������������������������������������������������������������������������������������������������������������� 304
xiv
■ Contents
Testing�������������������������������������������������������������������������������������������������������������������������� 344
GitHub��������������������������������������������������������������������������������������������������������������������������� 344
Conclusions������������������������������������������������������������������������������������������������������������������ 344
Data Science��������������������������������������������������������������������������������������������������������������������������������������� 345
Machine Learning������������������������������������������������������������������������������������������������������������������������������� 345
Data Analysis�������������������������������������������������������������������������������������������������������������������������������������� 345
R Programming����������������������������������������������������������������������������������������������������������������������������������� 345
Index��������������������������������������������������������������������������������������������������������������������� 347
xv
About the Author
Thomas Mailund is an associate professor in bioinformatics at Aarhus University, Denmark. His background
is in math and computer science, but for the last decade, his main focus has been on genetics and
evolutionary studies, particularly comparative genomics, speciation, and gene flow between emerging
species.
xvii
About the Technical Reviewer
xix
Acknowledgments
I would like to thank Asger Hobolth for many useful comments on earlier versions of this manuscript. He
helped me improve the writing and the presentation of the material.
xxi
Introduction
Welcome to Introduction to Data Science with R. This book was written as a set of lecture notes for two
classes I teach, Data Science: Visualization and Analysis and Data Science: Software Development and
Testing. The book is written to fit the structure of these classes, where each class consists of seven weeks of
lectures and project work. This means that there are 14 chapters with the core material, where the first seven
focus on data analysis and the last seven on developing reusable software for data science.
xxiii
■ Introduction
data, what purpose those changes serve, and how they help us gain knowledge about the data. It is as much
about deciding what to do with the data as it is about how to do it efficiently.
Statistics is of course also closely related to data science. So closely linked, in fact, that many consider
data science just a fancy word for statistics that looks slightly more modern and sexy. I can’t say that I
strongly disagree with this—data science does sound sexier than statistics—but just as data science is
slightly different from computer science, data science is also slightly different from statistics. Just, perhaps,
somewhat less different than computer science is.
A large part of doing statistics is building mathematical models for your data and fitting the models to
the data to learn about the data in this way. That is also what we do in data science. As long as the focus is on
the data, I am happy to call statistics data science. If the focus changes to the models and the mathematics,
then we are drifting away from data science into something else—just as if the focus changes from the data
to computations we are drifting from data science to computer science.
Data science is also related to machine learning and artificial intelligence, and again there are huge
overlaps. Perhaps not surprising since something like machine learning has its home both in computer
science and in statistics; if it is focusing on data analysis, it is also at home in data science. To be honest, it
has never been clear to me when a mathematical model changes from being a plain old statistical model to
becoming machine learning anyway.
For this book, we are just going to go with my definition and, as long as we are focusing on analyzing
data, we are going to call it data science.
xxiv
■ Introduction
For the final seven chapters of the book, the focus is on programming. To read this part you should
be familiar with object-oriented programming. I will explain how it is handled in R and how it differs from
languages such as Python, Java or C++ but I expect you to be familiar with terms such as class hierarchies,
inheritance, and polymorphic methods. I will not expect you to be already familiar with functional
programming (but if you are, there should still be plenty to learn in those chapters if you are not already
familiar with R programming as well).
xxv
■ Introduction
Software Development
Software and package development is then covered in the following seven chapters:
• Chapter 8, More R programming. In which you’ll return to the basics of R
programming and get a few more details than the tutorial in Chapter 1.
• Chapter 9, Advanced R programming. In which you explore more advanced
features of the R programming language, in particular, functional programming.
• Chapter 10, Object oriented programming. In which you learn how R models object
orientation and how you can use it to write more generic code.
• Chapter 11, Building an R package. In which you learn the necessary components of
an R package and how to program your own.
• Chapter 12, Testing and checking. In which you learn techniques for testing your R
code and checking the consistency of your R packages.
• Chapter 13, Version control. In which you learn how to manage code under version
control and how to collaborate using GitHub.
• Chapter 14, Profiling and optimizing. In which you learn how to identify hotspots
of code where inefficient solutions are slowing you down and techniques for
alleviating this.
These chapters are then followed by the second project, where you’ll build a package for Bayesian linear
regression.
Projects
You cannot learn how to analyze data without analyzing data, and you cannot learn how to develop software
without developing software either. Typing in examples from the book is nothing like writing code on your
own. Even doing exercises from the book—which you really ought to do—is not the same as working on your
own projects. Exercises, after all, cover small isolated aspects of problems you have just been introduced to.
In the real world, there is not a chapter of material presented before every task you have to deal with. You
need to work out by yourself what needs to be done and how. If you only do the exercises in this book, you
will miss the most important lessons in analyzing data. How to explore the data and get a feeling for it; how
to do the detective work necessary to pull out some understanding from the data; and how to deal with all
the noise and weirdness found in any dataset. And for developing a package, you need to think through how
to design and implement its functionality so that the various functions and data structures fit well together.
xxvi
■ Introduction
In this book, I go through a data analysis project to show you what that can look like. To actually
learn how to analyze data, you need to do it yourself as well, and you need to do it with a dataset that I
haven’t analyzed for you. You might have a dataset lying around you have worked on before, a dataset
from something you are just interested in, or you can probably find something interesting at a public data
repository, e.g., one of these:
• RDataMining.com
• UCI machine learning repository (http://archive.ics.uci.edu/ml/)
• KDNuggets (http://www.kdnuggets.com/datasets/index.html)
• Reddit r/datasets (https://www.reddit.com/r/datasets)
• GitHub awesome public datasets (https://github.com/caesar0301/awesome-
public-datasets)
I suggest that you find yourself a dataset and that after each lesson, you use the skills you have learned
to explore this dataset. Pick data that is structured as a table with observations as rows and variables as
columns, since that is the form of the data we consider in this book. At the end of the first seven chapters,
you will have analyzed this data, you can write a report about your analysis that others can evaluate to follow
and maybe modify it. You will be doing reproducible science.
For the programming topics, I describe another project illustrating the design and implementation
issues involved in making an R package. There, you should be able to learn from just implementing your
own version of the project I use, but you will, of course, be more challenged by working on a project without
any of my help at all. Whichever you do, to get the full benefit of this book you should make your own
package while reading the programming chapters.
xxvii
CHAPTER 1
Introduction to R Programming
We will use R for our data analysis so we need to know the basics of programming in the R language. R is a
full programming language with both functional programming and object oriented programming features.
Learning the language is far beyond the scope of this chapter and is something we return to later. The good
news, though, is that to use R for data analysis, you rarely need to do much programming. At least, if you do
the right kind of programming, you won’t need much.
For manipulating data—and how to do this is the topic of the next chapter—you mainly just have to
string together a couple of operations. Operations such as “group the data by this feature” followed by
“calculate the mean value of these features within each group” and then “plot these means”. This used to be
much more complicated to do in R, but a couple of new ideas on how to structure such data flow—and some
clever implementations of these in a couple of packages such as magrittr and dplyr—has significantly
simplified it. We will see some of this at the end of this chapter and more in the next chapter. First, though,
you need to get a taste for R.
Once you have opened RStudio, you can type R expressions into the console, which is the frame on
the left of the RStudio window. When you write an expression there, R will read it, evaluate it, and print the
result. When you assign values to variables, and you will see how to do this shortly, they will appear in the
Environment frame on the top right. At the bottom right, you have the directory where the project lives, and
files you create will go there.
To create a new file, choose File ➤ New File. You can select several different file types. We are interested
in the R Script and R Markdown types. The former is the file type for pure R code, while the latter is used for
creating reports where documentation text is mixed with R code. For data analysis projects, I recommend
using Markdown files. Writing documentation for what you are doing is really helpful when you need to go
back to a project several months down the line.
For most of this chapter, you can just write R code in the console, or you can create an R Script file. If
you create an R Script file, it will show up on the top left, as shown in Figure 1-2. You can evaluate single
expressions using the Run button on the top-right of this frame, or evaluate the entire file using the Source
button. For longer expressions, you might want to write them in an R Script file for now. In the next chapter,
we talk about R Markdown, which is the better solution for data science projects.
2
Chapter 1 ■ Introduction to R Programming
Using R as a Calculator
You can use the R console as a calculator where you just type in an expression you want calculated, press
Enter, and R gives you the result. You can play around with that a little bit to get familiar with how to write
expressions in R—there is some explanation for how to write them below—moving from using R as a
calculator in this sense to writing more sophisticated analysis programs is only a question of degree. A data
analysis program is really little more than a sequence of calculations, after all.
Simple Expressions
Simple arithmetic expressions are written, as in most other programming languages, in the typical
mathematical notation that you are used to.
1 + 2
## [1] 3
4 / 2
## [1] 2
(2 + 2) * 3
## [1] 12
3
Chapter 1 ■ Introduction to R Programming
It also works pretty much as you are used to. Except, perhaps, that you might be used to integers
behaving as integers in a division. At least in some programming languages, division between integers is
integer division, but in R, you can divide integers and if there is a remainder you will get a floating-point
number back as the result.
4 / 3
## [1] 1.333333
When you write numbers like 4 and 3, they are interpreted as floating-point numbers. To explicitly get
an integer, you must write 4L and 3L.
class(4)
## [1] "numeric"
class(4L)
## [1] "integer"
You will still get a floating-point if you divide two integers, although there is no need to tell R explicitly
that you want floating-point division. If you want integer division, on the other hand, you need a different
operator, %/%:
4 %/% 3
## [1] 1
In many languages % is used to get the remainder of a division, but this doesn’t quite work with R, where
% is used to construct infix operators. So in R, the operator for this is %%:
4 %% 3
## [1] 1
In addition to the basic arithmetic operators—addition, subtraction, multiplication, division, and the
modulus operator you just saw—you also have an exponentiation operator for taking powers. For this, you
can use ^ or ** as infix operators:
2^2
## [1] 4
2^3
## [1] 8
2**2
## [1] 4
2**3
## [1] 8
There are some other data types besides numbers, but we won’t go into an exhaustive list here. There
are two types you do need to know about early, though, since they are frequently used and since not knowing
about how they work can lead to all kinds of grief. Those are strings and “factors”.
Strings work as you would expect. You write them in quotes, either double quotes or single quotes, and
that is about it.
"hello,"
## [1] "hello,"
'world!'
## [1] "world!"
4
Chapter 1 ■ Introduction to R Programming
Strings are not particularly tricky, but I mention them because they look a lot like factors, but factors are
not like strings, they just look sufficiently like them to cause some confusion. I explain factors a little later in
this chapter when you have seen how functions and vectors work.
Assignments
To assign a value to a variable, you use the arrow operators. So you assign the value 2 to the variable x, you
would write the following:
x <- 2
x
## [1] 2
2 * x
## [1] 4
You can assign with arrows in both directions, so you could also write the following:
2 -> x
An assignment won’t print anything if you write it into the R terminal, but you can get R to print it just
by putting the assignment in parentheses.
x <- "invisible"
(y <- "visible")
## [1] "visible"
1:50
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
## [16] 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
## [31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
## [46] 46 47 48 49 50
5
Chapter 1 ■ Introduction to R Programming
Because we are essentially always working on vectors, there is one caveat I want to warn you about. If
you want to know the length of a string, you might—reasonably enough—think you can get that using the
length function. You would be wrong. That function gives you the length of a vector, so if you give it a single
string, it will always return 1.
length("qax")
## [1] 1
length("quux")
## [1] 1
length(c("foo", "barz"))
## [1] 2
In the last expression, we used the function c() to concatenate two strings. This creates a vector of
two strings, and thus the result of calling length on that is 2. To get the length of the actual string, you want
nchar instead:
nchar("qax")
## [1] 3
nchar("quux")
## [1] 4
nchar(c("foo", "barz"))
## [1] 3 4
Indexing Vectors
If you have a vector and want the i’th element of that vector, you can index the vector to get it like this:
(v <- 1:5)
## [1] 1 2 3 4 5
v[1]
## [1] 1
v[3]
## [1] 3
We have parentheses around the first expression to see the output of the operation. An assignment is
usually silent in R, but by putting the expression in parentheses, we make sure that R prints the result, which
is the vector of integers from 1 to 5. Notice here that the first element is at index 1. Many programming
languages start indexing at 0, but R starts indexing at 1. A vector of length n is thus indexed from 1 to n,
unlike in zero-indexed languages, where the indices go from 0 to n–1.
If you want to extract a subvector, you can also do this with indexing. You just use a vector of the indices
you want inside the square brackets. You can use the : operator for this or the concatenate function, c():
v[1:3]
## [1] 1 2 3
v[c(1,3,5)]
## [1] 1 3 5
You can even use a vector of Boolean values to pick out those values that are “true”:
6
Exploring the Variety of Random
Documents with Different Content
"In none of the enactments in 5 & 6 Vict. c. 45 will be found
anything which prejudicially affects the right of sole
representation conferred by the statute of 3 & 4 Will IV. c. 15.
The first production of a dramatic piece mentioned in section 20
of the statute of Victoria confers no priority upon the first
producer, nor does it confer a title to the sole liberty of
representation. That is conferred by the statute 3 & 4 Will. IV. c.
15 upon the author or his assignee: it[701] only fixes the first
production as the point from which (if entitled to it) the
endurance of the sole liberty of representation is to be
calculated."
The whole difficulty lies in the meaning of the words "first published"
as applied to the performing right. In Boucicault v. Delafield,[703]
and Boucicault v. Chatterton,[704] it was held that when an
unpublished play was first performed outside the British dominions
the performing right in this country was extinguished. "First
published" was held to include the "first performance" of a drama.
This, however, only provides for one possible contingency. As the
literary exchange with America, with which we have no international
convention, is becoming larger every year, it may be useful to
consider some of the other contingencies which may arise, and the
difficulties of which are not yet judicially solved. The cases
suggested are in connexion with the United States, but apply equally
to any foreign country, except in so far as rights may be acquired
under International Convention.
Duration of Protection.
As in the case of dramatic works, so in the case of musical
compositions it is submitted that the statutory protection dates from
composition, not from first public performance. Musical compositions
are protected under the same provisions which protect dramatic
works. The protection is therefore identical, except as to the[131]
two
amending statutes noticed below which do not apply to dramatic
works. It was contended in one case that the extension of 3 & 4
Will. IV. c. 15 to musical compositions was only applicable to musical
compositions of a dramatic nature.[708] This, however, is not the
case, and all musical compositions are protected.[709]
1. The title.
2. The name and place of abode of author or composer.
3. The name and place of abode of the proprietor.
4. The time and place of first representation.
1. The title.
2. The time of first publication.
3. The name and place of abode of the publisher.[714]
4. The name and place of abode of the proprietor.[715]
"I incline to think that this enactment was not meant to control
the operation of deeds of assignment, but only to regulate the
effect of entries in the registry book."[738]
By 3 & 4 Will. IV. c. 15, section 1, the author or his assignee has
"the sole liberty of representing, or causing to be represented, at
any place or places of dramatic entertainment whatsoever" in the
British dominions.
"It follows that as Crosby Hall was used for the public
representation for profit of a dramatic piece, it became a place
of dramatic entertainment for the time, within the statutes now
in question. The use for the time in question and not for a
former time is the essential fact. As a regular theatre may be a
lecture-room, dining-room, ball-room, and concert-room on
successive days, so a room used ordinarily for either of these
purposes would become for the time being a theatre if used for
the representation of a regular stage play. In this sense, as "The
Ship on Fire" was a dramatic piece, in our view Crosby Hall,
when used for the public representation and performance of it
for profit, became a place of dramatic entertainment. In thus
deciding we do not declare that the defendant's performances
at Crosby Hall were unlawful without a theatrical licence within
Stat. 6 & 7 Vict. c. 68."[745]
"I think the answer is this, that what is called in the argument a
'condition' of recovering a penalty in sec. 2 of 3 & 4 Will. IV. c.
15 is nothing of the kind, but part of the definition of the
offence upon which the penalty is to be incurred.... The right
granted is the privilege of representing at places of dramatic
entertainment.... Now sec. 20 of 5 & 6 Vict. c. 45 creates a new
right of property as to a musical composition, and gives the
author and his assigns the sole liberty of representing or
performing it. That is the right given, and sec. 21 says that the
person who shall have that right 'shall have and enjoy the
remedies given and provided' in the Act of 3 & 4 Will. IV. c. 15.
Why read into that word 'remedies' that the second section of
that Act is only to be put in force not where there is an
infringement of that right, but where there has been a
representation or performance at a place of dramatic
entertainment."
The view of Cotton, L. J., in the same case was that the remedies of
3 & 4 Will. IV. c. 15 were not applicable unless the musical
composition was performed in a place of dramatic entertainment;
but that in every case of public performance there was a remedy
under 5 & 6 Vict. c. 45 for damages and injunction. Since the
Musical Copyright Act of 1888 the distinction between these opinions
has become immaterial, for in every case in which the performance
is actionable at all the Court may assess the damages as it thinks
proper.
Performing Rights.
An action for—
1. Penalty[777] of 40s. for each performance, or the
defendant's profits, or the actual damage sustained,
whichever be the greater.
2. Injunction.[778]
3. A full and reasonable indemnity as to costs.[779]
Performing Rights..
An action for—
1. Damages.[781]
2. Injunction.[782]
3. Costs in the discretion of the Court.[783]
COPYRIGHT IN ENGRAVINGS
"It was reasonable and proper to take a map out of the class of
artistic copyrights and to give to it the better and more
complete copyright which is intended to be given to literary
works. And there would be, as I have pointed out clearly, great
inconvenience in having two laws of copyright as to two sets of
maps or as to the same set of maps."[798]
"It is plain that the object of the legislature was to protect those
works which were designed, engraved, etched, or worked in
Great Britain, and not those which were designed, engraved,
etched, or worked abroad, and only published in Great Britain."
[804]
The Act 6 & 7 Will. IV. c. 59 extends the application of the Engraving
Acts to Ireland, and in section 2 there is a general proviso protecting
"any engraving or print of any description whatever ... which may
have been or which shall hereafter be published in any part of Great
Britain or Ireland." It is quite arguable that this extends the
protection to engravings wherever made if published in the United
Kingdom; but probably it would be held to be only applicable to
engravings made in the United Kingdom, and is merely a proviso
that there will be no copyright until publication in the United
Kingdom. The point, however, is one of great uncertainty.
But Buller, J., in the same case, thought the proprietor always meant
the inventor and first proprietor, notwithstanding the property had
passed to his assignee. The point is certainly doubtful, but the latter
view that the name of the first proprietor only need be on the print
seems the more reasonable, and not contrary to the wording of the
Act. The proprietor need not be described as such on the plate.[816]
If his name is there it is sufficient, even if there is more than one
name and it is uncertain which is the proprietor.[817] The proprietor
need not be described by his full name, his surname is sufficient.
[818] When a partnership firm are proprietors of an engraving the
trading name of the firm is a sufficient designation, inasmuch as it
enables parties to know whom to apply to for information.[819] If a
single proprietor trades under the designation of A. B. & Co. that is a
sufficient designation.[820]
For any such offence the remedy is an action in the High Court for—
i. Forfeiture of plates and sheets to proprietor for destruction.
[837]
Further it is an offence—
For any such offence the remedy is an action in the High Court for—
i. Damages.[844]
ii. Injunction.[845]
iii. Inspection and Account.[846]
[156]
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com