Docsity

Introductory Statistics with R, Notas de estudo de Estatística

Pré-visualização parcial do texto

Baixe Introductory Statistics with R e outras Notas de estudo em PDF para Estatística, somente na Docsity!

Statistics and Computing

Series Editors:

J. Chambers

D. Hand

W. H¨ardle

Peter Dalgaard

Introductory Statistics with R

Second Edition

Peter Dalgaard Department of Biostatistics University of Copenhagen Denmark [email protected]

ISSN: 1431- ISBN: 978-0-387-79053-4 e-ISBN: 978-0-387-79054- DOI: 10.1007/978-0-387-79054-

Library of Congress Control Number: 2008932040

©c 2008 Springer Science+Business Media, LLC All rights reserved. This work may not be translated or copied in whole or in part without the written permission of the publisher (Springer Science+Business Media, LLC, 233 Spring Street, New York, NY 10013, USA), except for brief excerpts in connection with reviews or scholarly analysis. Use in connection with any form of information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed is forbidden. 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.

Printed on acid-free paper

springer.com

Preface

R is a statistical computer program made available through the Internet under the General Public License (GPL). That is, it is supplied with a li- cense that allows you to use it freely, distribute it, or even sell it, as long as the receiver has the same rights and the source code is freely available. It exists for Microsoft Windows XP or later, for a variety of Unix and Linux platforms, and for Apple Macintosh OS X.

R provides an environment in which you can perform statistical analysis and produce graphics. It is actually a complete programming language, although that is only marginally described in this book. Here we content ourselves with learning the elementary concepts and seeing a number of cookbook examples.

R is designed in such a way that it is always possible to do further computations on the results of a statistical procedure. Furthermore, the design for graphical presentation of data allows both no-nonsense meth- ods, for example plot(x,y), and the possibility of fine-grained control of the output’s appearance. The fact that R is based on a formal computer language gives it tremendous flexibility. Other systems present simpler interfaces in terms of menus and forms, but often the apparent user- friendliness turns into a hindrance in the longer run. Although elementary statistics is often presented as a collection of fixed procedures, analysis of moderately complex data requires ad hoc statistical model building, which makes the added flexibility of R highly desirable.

viii Preface

R owes its name to typical Internet humour. You may be familiar with the programming language C (whose name is a story in itself). Inspired by this, Becker and Chambers chose in the early 1980s to call their newly developed statistical programming language S. This language was further developed into the commercial product S-PLUS, which by the end of the decade was in widespread use among statisticians of all kinds. Ross Ihaka and Robert Gentleman from the University of Auckland, New Zealand, chose to write a reduced version of S for teaching purposes, and what was more natural than choosing the immediately preceding letter? Ross’ and Robert’s initials may also have played a role.

In 1995, Martin Maechler persuaded Ross and Robert to release the source code for R under the GPL. This coincided with the upsurge in Open Source software spurred by the Linux system. R soon turned out to fill a gap for people like me who intended to use Linux for statistical computing but had no statistical package available at the time. A mailing list was set up for the communication of bug reports and discussions of the development of R.

In August 1997, I was invited to join an extended international core team whose members collaborate via the Internet and that has controlled the development of R since then. The core team was subsequently expanded several times and currently includes 19 members. On February 29, 2000, version 1.0.0 was released. As of this writing, the current version is 2.6.2.

This book was originally based upon a set of notes developed for the course in Basic Statistics for Health Researchers at the Faculty of Health Sciences of the University of Copenhagen. The course had a primary tar- get of students for the Ph.D. degree in medicine. However, the material has been substantially revised, and I hope that it will be useful for a larger audience, although some biostatistical bias remains, particularly in the choice of examples.

In later years, the course in Statistical Practice in Epidemiology, which has been held yearly in Tartu, Estonia, has been a major source of inspiration and experience in introducing young statisticians and epidemiologists to R.

This book is not a manual for R. The idea is to introduce a number of basic concepts and techniques that should allow the reader to get started with practical statistics.

In terms of the practical methods, the book covers a reasonable curriculum for first-year students of theoretical statistics as well as for engineering students. These groups will eventually need to go further and study more complex models as well as general techniques involving actual programming in the R language.

x Preface

typesetting of this book, TEX, LATEX, and the consolidating efforts of the LATEX2e project have been indispensable.

Peter Dalgaard Copenhagen April 2008

Contents

  • 1 Basics Preface vii
    • 1.1 First steps
      • 1.1.1 An overgrown calculator
      • 1.1.2 Assignments
      • 1.1.3 Vectorized arithmetic
      • 1.1.4 Standard procedures
      • 1.1.5 Graphics
    • 1.2 R language essentials
      • 1.2.1 Expressions and objects
      • 1.2.2 Functions and arguments
      • 1.2.3 Vectors
      • 1.2.4 Quoting and escape sequences
      • 1.2.5 Missing values
      • 1.2.6 Functions that create vectors
      • 1.2.7 Matrices and arrays
      • 1.2.8 Factors
      • 1.2.9 Lists
      • 1.2.10 Data frames
      • 1.2.11 Indexing
      • 1.2.12 Conditional selection
      • 1.2.13 Indexing of data frames
      • 1.2.14 Grouped data and data frames
      • 1.2.15 Implicit loops xii Contents
      • 1.2.16 Sorting
    • 1.3 Exercises
  • 2 The R environment
    • 2.1 Session management
      • 2.1.1 The workspace
      • 2.1.2 Textual output
      • 2.1.3 Scripting
      • 2.1.4 Getting help
      • 2.1.5 Packages
      • 2.1.6 Built-in data
      • 2.1.7 attach and detach
      • 2.1.8 subset, transform, and within
    • 2.2 The graphics subsystem
      • 2.2.1 Plot layout
      • 2.2.2 Building a plot from pieces
      • 2.2.3 Using par
      • 2.2.4 Combining plots
    • 2.3 R programming
      • 2.3.1 Flow control
      • 2.3.2 Classes and generic functions
    • 2.4 Data entry
      • 2.4.1 Reading from a text file
      • 2.4.2 Further details on read.table
      • 2.4.3 The data editor
      • 2.4.4 Interfacing to other programs
    • 2.5 Exercises
  • 3 Probability and distributions
    • 3.1 Random sampling
    • 3.2 Probability calculations and combinatorics
    • 3.3 Discrete distributions
    • 3.4 Continuous distributions
    • 3.5 The built-in distributions in R
      • 3.5.1 Densities
      • 3.5.2 Cumulative distribution functions
      • 3.5.3 Quantiles
      • 3.5.4 Random numbers
    • 3.6 Exercises
  • 4 Descriptive statistics and graphics
    • 4.1 Summary statistics for a single group
    • 4.2 Graphical display of distributions
      • 4.2.1 Histograms
      • 4.2.2 Empirical cumulative distribution Contents xiii
      • 4.2.3 Q–Q plots
      • 4.2.4 Boxplots
    • 4.3 Summary statistics by groups
    • 4.4 Graphics for grouped data
      • 4.4.1 Histograms
      • 4.4.2 Parallel boxplots
      • 4.4.3 Stripcharts
    • 4.5 Tables
      • 4.5.1 Generating tables
      • 4.5.2 Marginal tables and relative frequency
    • 4.6 Graphical display of tables
      • 4.6.1 Barplots
      • 4.6.2 Dotcharts
      • 4.6.3 Piecharts
    • 4.7 Exercises
  • 5 One- and two-sample tests
    • 5.1 One-sample t test
    • 5.2 Wilcoxon signed-rank test
    • 5.3 Two-sample t test
    • 5.4 Comparison of variances
    • 5.5 Two-sample Wilcoxon test
    • 5.6 The paired t test
    • 5.7 The matched-pairs Wilcoxon test
    • 5.8 Exercises
  • 6 Regression and correlation
    • 6.1 Simple linear regression
    • 6.2 Residuals and fitted values
    • 6.3 Prediction and confidence bands
    • 6.4 Correlation
      • 6.4.1 Pearson correlation
      • 6.4.2 Spearman’s ρ
      • 6.4.3 Kendall’s τ
    • 6.5 Exercises
  • 7 Analysis of variance and the Kruskal–Wallis test
    • 7.1 One-way analysis of variance
      • 7.1.1 Pairwise comparisons and multiple testing
      • 7.1.2 Relaxing the variance assumption
      • 7.1.3 Graphical presentation
      • 7.1.4 Bartlett’s test
    • 7.2 Kruskal–Wallis test
    • 7.3 Two-way analysis of variance
      • 7.3.1 Graphics for repeated measurements xiv Contents
    • 7.4 The Friedman test
    • 7.5 The ANOVA table in regression analysis
    • 7.6 Exercises
  • 8 Tabular data
    • 8.1 Single proportions
    • 8.2 Two independent proportions
    • 8.3 k proportions, test for trend
    • 8.4 r × c tables
    • 8.5 Exercises
  • 9 Power and the computation of sample size
    • 9.1 The principles of power calculations
      • 9.1.1 Power of one-sample and paired t tests
      • 9.1.2 Power of two-sample t test
      • 9.1.3 Approximate methods
      • 9.1.4 Power of comparisons of proportions
    • 9.2 Two-sample problems
    • 9.3 One-sample problems and paired tests
    • 9.4 Comparison of proportions
    • 9.5 Exercises
  • 10 Advanced data handling
    • 10.1 Recoding variables
      • 10.1.1 The cut function
      • 10.1.2 Manipulating factor levels
      • 10.1.3 Working with dates
      • 10.1.4 Recoding multiple variables
    • 10.2 Conditional calculations
    • 10.3 Combining and restructuring data frames
      • 10.3.1 Appending frames
      • 10.3.2 Merging data frames
      • 10.3.3 Reshaping data frames
    • 10.4 Per-group and per-case procedures
    • 10.5 Time splitting
    • 10.6 Exercises
  • 11 Multiple regression
    • 11.1 Plotting multivariate data
    • 11.2 Model specification and output
    • 11.3 Model search
    • 11.4 Exercises
  • 12 Linear models Contents xv
    • 12.1 Polynomial regression
    • 12.2 Regression through the origin
    • 12.3 Design matrices and dummy variables
    • 12.4 Linearity over groups
    • 12.5 Interactions
    • 12.6 Two-way ANOVA with replication
    • 12.7 Analysis of covariance
      • 12.7.1 Graphical description
      • 12.7.2 Comparison of regression lines
    • 12.8 Diagnostics
    • 12.9 Exercises
  • 13 Logistic regression
    • 13.1 Generalized linear models
    • 13.2 Logistic regression on tabular data
      • 13.2.1 The analysis of deviance table
      • 13.2.2 Connection to test for trend
    • 13.3 Likelihood profiling
    • 13.4 Presentation as odds-ratio estimates
    • 13.5 Logistic regression using raw data
    • 13.6 Prediction
    • 13.7 Model checking
    • 13.8 Exercises
  • 14 Survival analysis
    • 14.1 Essential concepts
    • 14.2 Survival objects
    • 14.3 Kaplan–Meier estimates
    • 14.4 The log-rank test
    • 14.5 The Cox proportional hazards model
    • 14.6 Exercises
  • 15 Rates and Poisson regression
    • 15.1 Basic ideas
      • 15.1.1 The Poisson distribution
      • 15.1.2 Survival analysis with constant hazard
    • 15.2 Fitting Poisson models
    • 15.3 Computing rates
    • 15.4 Models with piecewise constant intensities
    • 15.5 Exercises
  • 16 Nonlinear curve fitting
    • 16.1 Basic usage
    • 16.2 Finding starting values
    • 16.3 Self-starting models xvi Contents
    • 16.4 Profiling
    • 16.5 Finer control of the fitting algorithm
    • 16.6 Exercises
  • A Obtaining and installing R and the ISwR package
  • B Data sets in the ISwR package
  • C Compendium
  • D Answers to exercises
  • Bibliography
  • Index

1

Basics

The purpose of this chapter is to get you started using R. It is assumed that you have a working installation of the software and of the ISwR package that contains the data sets for this book. Instructions for obtaining and installing the software are given in Appendix A.

The text that follows describes R version 2.6.2. As of this writing, that is the latest version of R. As far as possible, I present the issues in a way that is independent of the operating system in use and assume that the reader has the elementary operational knowledge to select from menus, move windows around, etc. I do, however, make exceptions where I am aware of specific difficulties with a particular platform or specific features of it.

1.1 First steps

This section gives an introduction to the R computing environment and walks you through its most basic features.

Starting R is straightforward, but the method will depend on your com- puting platform. You will be able to launch it from a system menu, by double-clicking an icon, or by entering the command “R” at the system command line. This will either produce a console window or cause R to start up as an interactive program in the current terminal window. In

P. Dalgaard, Introductory Statistics with R, DOI: 10.1007/978-0-387-79054-1_1, © Springer Science+Business Media, LLC 2008

1.1 First steps 3

of commands will fall naturally, it is necessary to introduce some concepts and conventions through simpler examples.

Under Windows, the graphics window will have taken the keyboard focus at this point. Click on the console to make it accept further commands.

1.1.1 An overgrown calculator

One of the simplest possible tasks in R is to enter an arithmetic expression and receive a result. (The second line is the answer from the machine.)

2 + 2 [1] 4

So the machine knows that 2 plus 2 makes 4. Of course, it also knows how to do other standard calculations. For instance, here is how to compute e−^2 :

exp(-2) [1] 0.

The [1] in front of the result is part of R’s way of printing numbers and vectors. It is not useful here, but it becomes so when the result is a longer vector. The number in brackets is the index of the first number on that line. Consider the case of generating 15 random numbers from a normal distribution:

rnorm(15) [1] -0.18326112 -0.59753287 -0.67017905 0.16075723 1. [6] 0.07976977 0.13683303 0.77155246 0.85986694 -1. [11] -0.49448567 0.52433026 1.07732656 1.09748097 -1.

Here, for example, the [6] indicates that 0.07976977 is the sixth element in the vector. (For typographical reasons, the examples in this book are made with a shortened line width. If you try it on your own machine, you will see the values printed with six numbers per line rather than five. The num- bers themselves will also be different since random number generation is involved.)

1.1.2 Assignments

Even on a calculator, you will quickly need some way to store intermedi- ate results, so that you do not have to key them in over and over again. R, like other computer languages, has symbolic variables, that is names that

4 1. Basics

can be used to represent values. To assign the value 2 to the variable x, you can enter

x <- 2

The two characters <- should be read as a single symbol: an arrow point- ing to the variable to which the value is assigned. This is known as the assignment operator. Spacing around operators is generally disregarded by R, but notice that adding a space in the middle of a <- changes the meaning to “less than” followed by “minus” (conversely, omitting the space when comparing a variable to a negative number has unexpected consequences!).

There is no immediately visible result, but from now on, x has the value 2 and can be used in subsequent arithmetic expressions.

x [1] 2 x + x [1] 4

Names of variables can be chosen quite freely in R. They can be built from letters, digits, and the period (dot) symbol. There is, however, the limita- tion that the name must not start with a digit or a period followed by a digit. Names that start with a period are special and should be avoided. A typical variable name could be height.1yr, which might be used to describe the height of a child at the age of 1 year. Names are case-sensitive: WT and wt do not refer to the same variable.

Some names are already used by the system. This can cause some con- fusion if you use them for other purposes. The worst cases are the single-letter names c, q, t, C, D, F, I, and T, but there are also diff, df, and pt, for example. Most of these are functions and do not usually cause trouble when used as variable names. However, F and T are the standard abbreviations for FALSE and TRUE and no longer work as such if you redefine them.

1.1.3 Vectorized arithmetic

You cannot do much statistics on single numbers! Rather, you will look at data from a group of patients, for example. One strength of R is that it can handle entire data vectors as single objects. A data vector is simply an array of numbers, and a vector variable can be constructed like this:

weight <- c(60, 72, 57, 90, 95, 72) weight [1] 60 72 57 90 95 72