Beginning R An Introduction to Statistical Programming 2nd ed. Edition Larry Pace 2024 scribd download
Beginning R An Introduction to Statistical Programming 2nd ed. Edition Larry Pace 2024 scribd download
com
https://ebookname.com/product/beginning-r-an-introduction-
to-statistical-programming-2nd-ed-edition-larry-pace/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/an-introduction-to-bioceramics-2nd-
edition-larry-l-hench/
ebookname.com
https://ebookname.com/product/introduction-to-criminal-justice-16th-
ed-edition-larry-j-siegel/
ebookname.com
https://ebookname.com/product/beginning-programming-with-java-for-
dummies-2nd-ed-edition-barry-a-burd/
ebookname.com
https://ebookname.com/product/safe-management-of-wastes-from-health-
care-activities-a-practical-guide-2nd-ed-edition-j/
ebookname.com
Democratization in Africa Challenges and Prospects 1st
Edition Gordon Crawford
https://ebookname.com/product/democratization-in-africa-challenges-
and-prospects-1st-edition-gordon-crawford/
ebookname.com
https://ebookname.com/product/starting-strength-basic-barbell-
training-3rd-ed-edition-mark-rippetoe/
ebookname.com
https://ebookname.com/product/agrobacterium-protocols-2nd-edition-kan-
wang-ed/
ebookname.com
https://ebookname.com/product/exploring-the-powers-of-your-inner-mind-
jaime-t-licauco/
ebookname.com
Elusive Togetherness Church Groups Trying to Bridge
America s Divisions Paul Lichterman
https://ebookname.com/product/elusive-togetherness-church-groups-
trying-to-bridge-america-s-divisions-paul-lichterman/
ebookname.com
Beginning R
An Introduction to Statistical
Programming
Second Edition
■
■Chapter 1: Getting Star ted������������������������������������������������������������������������������������� 1
■
■Chapter 2: Dealing with Dates, Strings, and Data Frames����������������������������������� 15
■
■Chapter 3: Input and Output�������������������������������������������������������������������������������� 27
■
■Chapter 4: Control Structures������������������������������������������������������������������������������ 35
■
■Chapter 5: Functional Programming������������������������������������������������������������������� 43
■
■Chapter 6: Probability Distributions�������������������������������������������������������������������� 53
■
■Chapter 7: Working with Tables��������������������������������������������������������������������������� 67
■
■Chapter 8: Descriptive Statistics and Exploratory Data Analysis������������������������ 73
■
■Chapter 9: Working with Graphics����������������������������������������������������������������������� 81
■
■Chapter 10: Traditional Statistical Methods�������������������������������������������������������� 93
■
■Chapter 11: Modern Statistical Methods����������������������������������������������������������� 101
■
■Chapter 12: Analysis of Variance���������������������������������������������������������������������� 111
■
■Chapter 13: Correlation and Regression������������������������������������������������������������ 121
■
■Chapter 14: Multiple Regression����������������������������������������������������������������������� 139
■
■Chapter 15: Logistic Regression������������������������������������������������������������������������ 163
v
■ Contents at a Glance
■
■Chapter 16: Modern Statistical Methods II�������������������������������������������������������� 193
■
■Chapter 17: Data Visualization Cookbook��������������������������������������������������������� 215
■
■Chapter 18: High-Performance Computing�������������������������������������������������������� 279
■
■Chapter 19: Text Mining������������������������������������������������������������������������������������ 303
Index��������������������������������������������������������������������������������������������������������������������� 321
vi
Contents
■
■Chapter 1: Getting Star ted������������������������������������������������������������������������������������� 1
1.1 What is R, Anyway?���������������������������������������������������������������������������������������������������� 1
1.2 A First R Session�������������������������������������������������������������������������������������������������������� 3
1.3 Your Second R Session����������������������������������������������������������������������������������������������� 6
1.3.1 Working with Indexes�������������������������������������������������������������������������������������������������������������������� 6
1.3.2 Representing Missing Data in R���������������������������������������������������������������������������������������������������� 7
1.3.3 Vectors and Vectorization in R������������������������������������������������������������������������������������������������������� 8
1.3.4 A Brief Introduction to Matrices����������������������������������������������������������������������������������������������������� 9
1.3.5 More on Lists������������������������������������������������������������������������������������������������������������������������������� 11
1.3.6 A Quick Introduction to Data Frames������������������������������������������������������������������������������������������� 12
■
■Chapter 2: Dealing with Dates, Strings, and Data Frames����������������������������������� 15
2.1 Working with Dates and Times��������������������������������������������������������������������������������� 15
2.2 Working with Strings������������������������������������������������������������������������������������������������ 16
2.3 Working with Data Frames in the Real World����������������������������������������������������������� 18
2.3.1 Finding and Subsetting Data������������������������������������������������������������������������������������������������������� 19
vii
■ Contents
■
■Chapter 3: Input and Output�������������������������������������������������������������������������������� 27
3.1 R Input���������������������������������������������������������������������������������������������������������������������� 27
3.1.1 The R Editor��������������������������������������������������������������������������������������������������������������������������������� 28
3.1.2 The R Data Editor������������������������������������������������������������������������������������������������������������������������� 29
3.1.3 Other Ways to Get Data Into R����������������������������������������������������������������������������������������������������� 30
3.1.4 Reading Data from a File������������������������������������������������������������������������������������������������������������� 31
3.1.5 Getting Data from the Web���������������������������������������������������������������������������������������������������������� 31
3.2 R Output������������������������������������������������������������������������������������������������������������������� 33
3.2.1 Saving Output to a File���������������������������������������������������������������������������������������������������������������� 33
■
■Chapter 4: Control Structures������������������������������������������������������������������������������ 35
4.1 Using Logic��������������������������������������������������������������������������������������������������������������� 35
4.2 Flow Control������������������������������������������������������������������������������������������������������������� 36
4.2.1 Explicit Looping��������������������������������������������������������������������������������������������������������������������������� 36
4.2.2 Implicit Looping��������������������������������������������������������������������������������������������������������������������������� 38
viii
■ Contents
■
■Chapter 6: Probability Distributions�������������������������������������������������������������������� 53
6.1 Discrete Probability Distributions����������������������������������������������������������������������������� 53
6.2 The Binomial Distribution����������������������������������������������������������������������������������������� 54
6.2.1 The Poisson Distribution�������������������������������������������������������������������������������������������������������������� 57
6.2.2 Some Other Discrete Distributions���������������������������������������������������������������������������������������������� 58
References��������������������������������������������������������������������������������������������������������������������� 65
■
■Chapter 7: Working with Tables��������������������������������������������������������������������������� 67
7.1 Working with One-Way Tables���������������������������������������������������������������������������������� 67
7.2 Working with Two-Way Tables���������������������������������������������������������������������������������� 71
■
■Chapter 8: Descriptive Statistics and Exploratory Data Analysis������������������������ 73
8.1 Central Tendency������������������������������������������������������������������������������������������������������ 73
8.1.1 The Mean������������������������������������������������������������������������������������������������������������������������������������� 73
8.1.2 The Median���������������������������������������������������������������������������������������������������������������������������������� 74
8.1.3 The Mode������������������������������������������������������������������������������������������������������������������������������������� 75
8.2 Variability������������������������������������������������������������������������������������������������������������������ 76
8.2.1 The Range������������������������������������������������������������������������������������������������������������������������������������ 76
8.2.2 The Variance and Standard Deviation������������������������������������������������������������������������������������������ 77
ix
■ Contents
■
■Chapter 9: Working with Graphics����������������������������������������������������������������������� 81
9.1 Creating Effective Graphics�������������������������������������������������������������������������������������� 81
9.2 Graphing Nominal and Ordinal Data������������������������������������������������������������������������� 82
9.3 Graphing Scale Data������������������������������������������������������������������������������������������������� 84
9.3.1 Boxplots Revisited����������������������������������������������������������������������������������������������������������������������� 84
9.3.2 Histograms and Dotplots������������������������������������������������������������������������������������������������������������� 86
9.3.3 Frequency Polygons and Smoothed Density Plots����������������������������������������������������������������������� 87
9.3.4 Graphing Bivariate Data��������������������������������������������������������������������������������������������������������������� 89
References��������������������������������������������������������������������������������������������������������������������� 92
■
■Chapter 10: Traditional Statistical Methods�������������������������������������������������������� 93
10.1 Estimation and Confidence Intervals���������������������������������������������������������������������� 93
10.1.1 Confidence Intervals for Means������������������������������������������������������������������������������������������������� 93
10.1.2 Confidence Intervals for Proportions����������������������������������������������������������������������������������������� 94
10.1.3 Confidence Intervals for the Variance���������������������������������������������������������������������������������������� 95
x
■ Contents
■
■Chapter 12: Analysis of Variance���������������������������������������������������������������������� 111
12.1 Some Brief Background��������������������������������������������������������������������������������������� 111
12.2 One-Way ANOVA��������������������������������������������������������������������������������������������������� 112
12.3 Two-Way ANOVA��������������������������������������������������������������������������������������������������� 114
12.3.1 Repeated-Measures ANOVA����������������������������������������������������������������������������������������������������� 115
> results <- aov ( fitness ~ time + Error (id / time ), data = repeated) ��������������������������������������������� 116
12.3.2 Mixed-Model ANOVA���������������������������������������������������������������������������������������������������������������� 118
References������������������������������������������������������������������������������������������������������������������� 120
■
■Chapter 13: Correlation and Regression������������������������������������������������������������ 121
13.1 Covariance and Correlation���������������������������������������������������������������������������������� 121
13.2 Linear Regression: Bivariate Case������������������������������������������������������������������������ 123
13.3 An Extended Regression Example: Stock Screener���������������������������������������������� 129
13.3.1 Quadratic Model: Stock Screener�������������������������������������������������������������������������������������������� 131
13.3.2 A Note on Time Series������������������������������������������������������������������������������������������������������������� 134
xi
■ Contents
■
■Chapter 15: Logistic Regression������������������������������������������������������������������������ 163
15.1 The Mathematics of Logistic Regression������������������������������������������������������������� 163
15.2 Generalized Linear Models����������������������������������������������������������������������������������� 164
15.3 An Example of Logistic Regression���������������������������������������������������������������������� 165
15.3.1 What If We Tried a Linear Model on Age?�������������������������������������������������������������������������������� 166
15.3.2 Seeing If Age Might Be Relevant with Chi Square������������������������������������������������������������������� 167
15.3.3 Fitting a Logistic Regression Model���������������������������������������������������������������������������������������� 168
15.3.4 The Mathematics of Linear Scaling of Data����������������������������������������������������������������������������� 169
15.3.5 Logit Model with Rescaled Predictor��������������������������������������������������������������������������������������� 170
15.3.6 Multivariate Logistic Regression��������������������������������������������������������������������������������������������� 174
xii
■ Contents
■
■Chapter 17: Data Visualization Cookbook��������������������������������������������������������� 215
17.1 Required Packages���������������������������������������������������������������������������������������������� 215
17.2 Univariate Plots���������������������������������������������������������������������������������������������������� 215
17.3 Customizing and Polishing Plots�������������������������������������������������������������������������� 226
17.4 Multivariate Plots������������������������������������������������������������������������������������������������� 243
17.5 Multiple Plots������������������������������������������������������������������������������������������������������� 266
17.6 Three-Dimensional Graphs����������������������������������������������������������������������������������� 272
References������������������������������������������������������������������������������������������������������������������� 277
■
■Chapter 18: High-Performance Computing�������������������������������������������������������� 279
18.1 Data���������������������������������������������������������������������������������������������������������������������� 279
18.2 Parallel Processing����������������������������������������������������������������������������������������������� 293
18.2.1 Other Parallel Processing Approaches������������������������������������������������������������������������������������� 296
References������������������������������������������������������������������������������������������������������������������� 301
■
■Chapter 19: Text Mining������������������������������������������������������������������������������������ 303
19.1 Installing Needed Packages and Software����������������������������������������������������������� 304
19.1.1 Java����������������������������������������������������������������������������������������������������������������������������������������� 304
19.1.2 PDF Software��������������������������������������������������������������������������������������������������������������������������� 305
19.1.3 R Packages������������������������������������������������������������������������������������������������������������������������������ 305
19.1.4 Some Needed Files������������������������������������������������������������������������������������������������������������������ 305
Index��������������������������������������������������������������������������������������������������������������������� 321
xiii
About the Author
xv
In Memoriam
xvii
About the Technical Reviewer
xix
Acknowledgments
I would like to acknowledge my coauthor, Larry Pace. This book would never have been without him, and
my heart goes out to his family and friends.
I would also like to thank my brother, Matt, who spent many hours reading drafts and discussing how
best to convey the ideas. When I needed an opinion about how to phrase something, he unflinchingly
brought several ideas to the table (sometimes too many).
xxi
Introduction
This book is about the R programming language. Maybe more important, this book is for you.
These days, R is an impressively robust language for solving problems that lend themselves to statistical
programming methods. There is a large community of users and developers of this language, and together
we are able to accomplish things that were not possible before we virtually met.
Of course, to leverage this collective knowledge, we have to start somewhere. Chapters 1 through 5
focus on gaining familiarity with the R language itself. If you have prior experience in programming, these
chapters will be very easy for you. If you have no prior programming experience, that is perfectly fine.
We build from the ground up, and let us suggest you spend some thoughtful time here. Thinking like a
programmer has some very great advantages. It is a skill we would want you to have, and this book is,
after all, for you.
Chapters 6 through 10 focus on what might be termed elementary statistical methods in R. We did not
have the space to introduce those methods in their entirety—we are supposing some knowledge of statistics.
An introductory or elementary course for nonmajors would be more than enough. If you are already familiar
with programming and statistics, we suggest you travel through these chapters only briefly.
With Chapter 11, we break into the last part of the book. For someone with both a fair grasp of traditional
statistics and some programming experience, this may well be a good place to start. For our readers who
read through from the first pages, this is where it starts to get very exciting. From bootstrapping to logistic
regression to data visualization to high-performance computing, these last chapters have hands-on examples
that work through some much applied and very interesting examples.
One final note: While we wrote this text from Chapter 1 to Chapter 19 in order, the chapters are fairly
independent of each other. Don't be shy about skipping to the chapter you're most interested in learning.
We show all our code, and you may well be able to modify what we have to work with what you have.
Happy reading!
xxiii
Chapter 1
There are compelling reasons to use R. Enthusiastic users, programmers, and contributors support R and its
development. A dedicated core team of R experts maintains the language. R is accurate, produces excellent
graphics, has a variety of built-in functions, and is both a functional language and an object-oriented one.
There are (literally) thousands of contributed packages available to R users for specialized data analyses.
Developing from a novice into a more competent user of R may take as little as three months by only
using R on a part-time basis (disclaimer: n = 1). Realistically, depending on background, your development
may take days, weeks, months, or even a few years, depending on how often you use R and how quickly
you can learn its many intricacies. R users often develop into R programmers who write R functions, and R
programmers sometimes want to develop into R contributors, who write packages that help others with
their data analysis needs. You can stop anywhere on that journey you like, but if you finish this book and
follow good advice, you will be a competent R user who is ready to develop into a serious R programmer if
you want to do it. We wish you the best of luck!
http://cran.r-project.org/
Download and install the R binaries for your operating system, accepting all the defaults. At this writing,
the current version of R is 3.2.0, and in this book, you will see screenshots of R working in both Windows 7
and Windows 8.1. Your authors run on 64-bit operating systems, so you will see that information displayed
in the screen captures in this book. Because not everything R does in Unix-based systems can be done in
Windows, I often switch to Ubuntu to do those things, but we will discuss only the Windows applications
here, and leave you to experiment with Ubuntu or other flavors of Unix. One author runs Ubuntu on the
Amazon Cloud, but that is way beyond our current needs.
Go ahead and download Rstudio (current version as of this writing is 0.98.1103) now too, again,
accepting all defaults from the following URL:
http://www.rstudio.com/products/rstudio/download/
1
Chapter 1 ■ Getting Star ted
Rstudio is a very forgiving environment for the novice user, and code written in here will work just as
well in R itself.
Launch Rstudio and examine the resulting interface. Make sure that you can identify the following
parts of the R interface shown in Figure 1-1: the menu bar, the script editing area, the R console, and the
R command prompt, which is >.
Before we continue our first R session, let’s have a brief discussion of how R works. R is a high-level
vectorized computer language and statistical computing environment. You can write your own R code, use
R code written by others, and use R packages you write and those written by you or by others. You can use R
in batch mode, terminal mode, in the R graphical user interface (RGui), or in Rstudio, which is what we will
do in this book. As you learn more about R and how to use it effectively, you will find that you can integrate R
with other languages such as Python or C++, and even with other statistical programs such as SPSS.
In some computer languages, for instance, C++, you have to declare a data type before you assign a
value to a new variable, but that is not true in R. In R, you simply assign a value to the object, and you can
change the value or the data type by assigning a new one. There are two basic assignment operators in R.
The first is < −, a left-pointing assignment operator produced by a less than sign followed by a “minus” sign,
which is really a hyphen. You can also use an equals sign = for assignments in R. I prefer the < − assignment
operator, and will use it throughout this book.
You must use the = sign to assign the parameters in R functions, as you will learn. R is not sensitive to
white space the way some languages are, and the readability of R code is benefited from extra spacing and
indentation, although these are not mandatory. R is, however, case-sensitive, so to R, the variables x and X
are two different things. There are some reserved names in R, which I will tell you about in Chapter 5.
The best way to learn R is to use R, and there are many books, web-based tutorials, R blog sites, and
videos to help you with virtually any question you might have. We will begin with the basics in this book but
will quickly progress to the point that you are ready to become a purposeful R programmer, as mentioned
earlier.
2
Chapter 1 ■ Getting Star ted
Let us complete a five-minute session in R, and then delve into more detail about what we did, and
what R was doing behind the scenes. The most basic use of R is as a command-line interpreted language.
You type a command or statement after the R prompt and then press <Enter>, and R attempts to implement
the command. If R can do what you are asking, it will do it and return the result in the R console. If R
cannot do what you are asking, it will return an error message. Sometimes R will do something but give you
warnings, which are messages concerning what you have done and what the impact might be, but that are
sometimes warnings that what you did was not what you probably wanted to do. Always remember that R,
like any other computer language, cannot think for you.
> 1 + 1
[ 1 ] 2
> 1 ^ 1
[ 1 ] 1
> 1 * 1
[ 1 ] 1
> 1 - 1
[ 1 ] 0
> 1 : 1 0
[ 1 ] 1 2 3 4 5 6 7 8 9 1 0
> ( 1 : 1 0 ) ^ 2
[ 1 ] 1 4 9 1 6 2 5 3 6 4 9 6 4 8 1 1 0 0
> myName <- "Joshua Wiley"
> myAlmaMater <- "University of California, Los Angeles"
> myURL <- "www.JoshuaWiley.com"
> myPhone <- "1.260.673.5518"
> myData <- list(myName, myAlmaMater, myURL, myPhone)
> myData
[[1]]
[1] "Joshua Wiley"
[[2]]
[1] "University of California, Los Angeles"
[[3]]
[1] "www.JoshuaWiley.com"
[[4]]
[1] "1.260.673.5518"
We began with the use of R as a basic calculator. We can create sequences of integers by using the colon
operator. Using the exponentiation operator (1:10) ˆ2 gives us the squares of all the numbers in the vector
1 to 10. Observe that when you type a command and press the <Enter> key, R will return the result on the
next line, prefaced by an index, such as [1]. You can assign values to variables without declaring the variable
type, as we discussed, so you can just type myName < − "Joshua Wiley" to give the variable a value.
3
Chapter 1 ■ Getting Star ted
This might have seemed a strange way to start, but it shows you some of the things you can enter into
your R workspace simply by assigning them. Character strings must be enclosed in quotation marks, and
you can use either single or double quotes. Numbers can be assigned as they were with the myPhone variable.
With the name and address, we created a list, with is one of the basic data structures in R. Unlike vectors,
lists can contain multiple data types. We also see square brackets [ and ], which are R’s way to index the
elements of a data object, in this case our list. We can also create vectors, matrices, and data frames in R.
Let’s see how to save a vector of the numbers from 1 to 10. We will call the vector x. We will also create a
“constant” called y:
> x < - 1 : 1 0
> x
[ 1 ] 1 2 3 4 5 6 7 8 9 1 0
> y < - 5
> y
[ 1 ] 5
See that R starts its listing of both x and y with an index [1]. This is because R does not recognize a
scalar value. To R, even a single number is a vector. The object y is a vector with one element. The [1] in
front of x means that the first element of the vector appears at the beginning of the line. Let’s make another
vector, z, containing a sequence of 33 randomly generated numbers from a normal distribution with a mean
of 70 and a standard deviation of 10. Because the numbers are random, your z vector will not be the same as
mine, though if we wanted to, we could set the seed number in R so that we would both get the same vector:
> z < - r n o r m ( 3 3 , 70 , 1 0 )
> z < - r o u n d ( z , 2 )
> z
[ 1 ] 8 1 . 5 6 7 0 . 8 5 7 7 . 4 8 6 4 . 0 2 6 8 . 9 4 8 0 . 2 4 6 0 . 8 4
7 0 . 9 3 7 5 . 2 1 7 5 . 0 5 5 2 . 1 7 5 2 . 2 9
[ 1 3 ] 7 0 . 2 0 7 9 . 2 9 8 4 . 7 5 6 4 . 8 8 7 3 . 7 4 7 1 . 1 9 6 1 . 0 1
6 3 . 4 3 5 5 . 7 4 7 1 . 5 4 6 9 . 7 1 8 2 . 5 2
[ 2 5 ] 7 3 . 4 0 7 5 . 3 9 7 9 . 2 8 8 0 . 3 6 6 5 . 7 9 7 3 . 1 5 7 5 . 4 1
6 9 . 5 6 8 5 . 8 7
When R must wrap to a new line in the console to print additional output, it shows the index of the first
element of each line.
To see a list of all the objects in your R session, type the command ls():
> ls()
[1] "myAlmaMater" "myData" "myName" "myPhone" "myURL" "x" "y" "z"
To see the current working directory, type the command getwd(). You can change the working directory
by typing setwd(), but I usually find it easier to use the File menu. Just select File > Change dir... and
navigate to the directory you want to become the new working directory. As you can see from the code listing
here, the authors prefer working in the cloud. This allows us to gain access to our files from any Internet-
connected computer, tablet, or smartphone. Similarly, our R session is saved to the cloud, allowing access
from any of several computers at home or office computers.
> getwd()
[1] "C:/Users/Joshua Wiley/Google Drive/Projects/Books/Apress_BeginningR/BeginningR"
4
Chapter 1 ■ Getting Star ted
In addition to ls(), another helpful function is dir(), which will give you a list of the files in your current
working directory.
To quit your R session, simply type q() at the command prompt, or if you like to use the mouse, select
File > Exit or simply close Rstudio by clicking on the X in the upper right corner. In any of these cases, you
will be prompted to save your R workspace.
Go ahead and quit the current R session, and save your workspace when prompted. We will come
back to the same session in a few minutes. What was going on in the background while we played with R
was that R was recording everything you typed in the console and everything it wrote back to the console.
This is saved in an R history file. When you save your R session in an RData file, it contains this particular
workspace. When you find that file and open it, your previous workspace will be restored. This will keep you
from having to reenter your variables, data, and functions.
Before we go back to our R session, let’s see how to use R for some mathematical operators and
functions (see Table 1-1). These operators are vectorized, so they will apply to either single numbers or
vectors with more than one number, as we will discuss in more detail later in this chapter. According to the
R documentation, these are “unary and binary generic functions” that operate on numeric and complex
vectors, or vectors that can be coerced to numbers. For example, logical vectors of TRUE and FALSE are
coerced to integer vectors, with TRUE = 1 and FALSE = 0.
Table 1-2 shows R’s comparison operators. Each of these evaluates to a logical result of TRUE or FALSE.
We can abbreviate TRUE and FALSE as T and F, so it would be unwise to name a variable T or F, although R will
let you do that. Note that the equality operator == is different from the = used as an assignment operator. As
with the mathematical operators and the logical operators (see Chapter 4), these are also vectorized.
5
Chapter 1 ■ Getting Star ted
R has six “atomic” vector types (meaning that they cannot be broken down any further), including
logical, integer, real, complex, string (or character), and raw. Vectors must contain only one type of
data, but lists can contain any combination of data types. A data frame is a special kind of list and the most
common data object for statistical analysis. Like any list, a data frame can contain both numerical and
character information. Some character information can be used for factors. Working with factors can be a
bit tricky because they are “like” vectors to some extent, but they are not exactly vectors.
My friends who are programmers who dabble in statistics think factors are evil, while statisticians like
me who dabble in programming love the fact that character strings can be used as factors in R, because
such factors communicate group membership directly rather than indirectly. It makes more sense to have
a column in a data frame labeled sex with two entries, male and female, than it does to have a column
labeled sex with 0s and 1s in the data frame. If you like using 1s and 0s for factors, then use a scheme such as
labeling the column female and entering a 1 for a woman and 0 for a man. That way the 1 conveys meaning,
as does the 0. Note that some statistical software programs such as SPSS do not uniformly support the use of
strings as factors, whereas others, for example, Minitab, do.
In addition to vectors, lists, and data frames, R has language objects including calls, expressions, and
names. There are symbol objects and function objects, as well as expression objects. There is also a special
object called NULL, which is used to indicate that an object is absent. Missing data in R are indicated by NA,
which is also a valid logical object.
> x
[ 1 ] 1 2 3 4 5 6 7 8 9 1 0
> x [ 1 ]
[ 1 ] 1
> x [ 2 : 4 ]
[ 1 ] 2 3 4
> x [ - 1 0 ]
[ 1 ] 1 2 3 4 5 6 7 8 9
> x
[ 1 ] 1 2 3 4 5 6 7 8 9 1 0
> x [ 2 : 4 ] < - c ( 9 8 , 99 , 1 0 0 )
> x
[ 1 ] 1 9 8 9 9 1 0 0 5 6 7 8 9 1 0
6
Chapter 1 ■ Getting Star ted
Note that if you simply ask for subsets, the x vector is not changed, but if you reassign the subset or
modified vector, the changes are saved. Observe that the negative index removes the selected element
or elements from the vector but only changes the vector if you reassign the new vector to x. We can, if we
choose, give names to the elements of a vector, as this example shows:
> x < - 1 : 1 0
> x
[ 1 ] 1 2 3 4 5 6 7 8 9 1 0
> n a m e s ( x ) < - c ( " A " , " B " , " C " , " D " , " E " , " F " , " G " , " H " , "
I " , " J " )
> x
A B C D E F G H I J
1 2 3 4 5 6 7 8 9 1 0
This showcases the difference between thinking as a user versus thinking as a programmer! R has a
variety of built-in functions that automate even the simplest kind of operations. You just saw me waste
our time by typing in the letters A through J. R already knows the alphabet, and all you have to do is tell
R you want the first 10 letters. The more you know about R, the easier it is to work with, because it keeps
you from having to do a great deal of repetition in your programming. Take a look at what happens when
we ask R for the letters of the alphabet and use the power of built-in character manipulation functions to
make something a reproducible snippet of code. Everyone starts as an R user and (ideally) becomes an R
programmer, as discussed in the introduction:
> x
[ 1 ] 1 2 3 4 5 6 7 8 9 1 0
> n a m e s ( x ) < - t o u p p e r ( l e t t e r s [ 1 : 1 0 ] )
> x
A B C D E F G H I J
1 2 3 4 5 6 7 8 9 1 0
The toupper function coerces the letters to uppercase, and the letters[1:10] subset gives us A
through J. Always think like a programmer rather than a user. If you wonder if something is possible,
someone else has probably thought the same thing. Over two million people are using R right now, and
many of those people write R functions and code that automates the things that we use on such a regular
basis that we usually don’t even have to wonder whether but simply need to ask where they are and how to
use them. You can find many examples of efficient R code on the web, and the discussions on StackExchange
are very helpful.
If you are trying to figure something out that you don’t know how to do, don’t waste much time
experimenting. Use a web search engine, and you are very likely to find that someone else has already found
the solution, and has posted a helpful example you can use or modify for your own problem. The R manual
is also helpful, but only if you already have a strong programming background. Otherwise, it reads pretty
much like a technical manual on your new toaster written in a foreign language.
It is better to develop good habits in the beginning than it is to develop bad habits and then having to
break them first before you can learn good ones. This is what Dr. Lynda McCalman calls a BFO. That means a
blinding flash of the obvious. I have had many of those in my experience with R.
7
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of How to Get
Rich
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Author: Anonymous
Language: English
How
To Get Rich.
Smallest Magazine in the World. Subscription
price, 50 cts. per year. Single copies, 5 cents
each.
PUBLISHED BY
A. B. COURTNEY,
671 Tremont Street, Boston.
HOW TO GET RICH.
Valuable Money-Making Secrets.
These recipes have sold for five dollars
each, and have been the foundations of
many good-sized fortunes.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.