78,99 €
Hugely successful and popular text presenting an extensive and comprehensive guide for all R users
The R language is recognized as one of the most powerful and flexible statistical software packages, enabling users to apply many statistical techniques that would be impossible without such software to help implement such large data sets. R has become an essential tool for understanding and carrying out research.
This edition:
Praise for the first edition:
‘…if you are an R user or wannabe R user, this text is the one that should be on your shelf. The breadth of topics covered is unsurpassed when it comes to texts on data analysis in R.’ (The American Statistician, August 2008)
‘The High-level software language of R is setting standards in quantitative analysis. And now anybody can get to grips with it thanks to The R Book…’ (Professional Pensions, July 2007)Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1324
Veröffentlichungsjahr: 2012
Contents
Cover
Title Page
Copyright
Preface
Acknowledgements
Chapter 1: Getting Started
1.1 How to use this book
1.2 Installing R
1.3 Running R
1.4 The Comprehensive R Archive Network
1.5 Getting help in R
1.6 Packages in R
1.7 Command line versus scripts
1.8 Data editor
1.9 Changing the look of the R screen
1.10 Good housekeeping
1.11 Linking to other computer languages
Chapter 2: Essentials of the R Language
2.1 Calculations
2.2 Logical operations
2.3 Generating sequences
2.4 Membership: Testing and coercing in R
2.5 Missing values, infinity and things that are not numbers
2.6 Vectors and subscripts
2.7 Vector functions
2.8 Matrices and arrays
2.9 Random numbers, sampling and shuffling
2.10 Loops and repeats
2.11 Lists
2.12 Text, character strings and pattern matching
2.13 Dates and times in R
2.14 Environments
2.15 Writing R functions
2.16 Writing from R to file
2.17 Programming tips
Chapter 3: Data Input
3.1 Data input from the keyboard
3.2 Data input from files
3.3 Input from files using scan
3.4 Reading data from a file using readLines
3.5 Warnings when you attach the dataframe
3.6 Masking
3.7 Input and output formats
3.8 Checking files from the command line
3.9 Reading dates and times from files
3.10 Built-in data files
3.11 File paths
3.12 Connections
3.13 Reading data from an external database
Chapter 4: Dataframes
4.1 Subscripts and indices
4.2 Selecting rows from the dataframe at random
4.3 Sorting dataframes
4.4 Using logical conditions to select rows from the dataframe
4.5 Omitting rows containing missing values, NA
4.6 Using order and !duplicated to eliminate pseudoreplication
4.7 Complex ordering with mixed directions
4.8 A dataframe with row names instead of row numbers
4.9 Creating a dataframe from another kind of object
4.10 Eliminating duplicate rows from a dataframe
4.11 Dates in dataframes
4.12 Using the match function in dataframes
4.13 Merging two dataframes
4.14 Adding margins to a dataframe
4.15 Summarizing the contents of dataframes
Chapter 5: Graphics
5.1 Plots with two variables
5.2 Plotting with two continuous explanatory variables: Scatterplots
5.3 Adding other shapes to a plot
5.4 Drawing mathematical functions
5.5 Shape and size of the graphics window
5.6 Plotting with a categorical explanatory variable
5.7 Plots for single samples
5.8 Plots with multiple variables
5.9 Special plots
5.10 Saving graphics to file
5.11 Summary
Chapter 6: Tables
6.1 Tables of counts
6.2 Summary tables
6.3 Expanding a table into a dataframe
6.4 Converting from a dataframe to a table
6.5 Calculating tables of proportions with prop.table
6.6 The scale function
6.7 The expand.grid function
6.8 The model.matrix function
6.9 Comparing table and tabulate
Chapter 7: Mathematics
7.1 Mathematical functions
7.2 Probability functions
7.3 Continuous probability distributions
7.4 Discrete probability distributions
7.5 Matrix algebra
7.6 Solving systems of linear equations using matrices
7.7 Calculus
Chapter 8: Classical Tests
8.1 Single samples
8.2 Bootstrap in hypothesis testing
8.3 Skew and kurtosis
8.4 Two samples
8.5 Tests on paired samples
8.6 The sign test
8.7 Binomial test to compare two proportions
8.8 Chi-squared contingency tables
8.9 Correlation and covariance
8.10 Kolmogorov–Smirnov test
8.11 Power analysis
8.12 Bootstrap
Chapter 9: Statistical Modelling
9.1 First things first
9.2 Maximum likelihood
9.3 The principle of parsimony (Occam's razor)
9.4 Types of statistical model
9.5 Steps involved in model simplification
9.6 Model formulae in R
9.7 Multiple error terms
9.8 The intercept as parameter 1
9.9 The update function in model simplification
9.10 Model formulae for regression
9.11 Box–Cox transformations
9.12 Model criticism
9.13 Model checking
9.14 Influence
9.15 Summary of statistical models in R
9.16 Optional arguments in model-fitting functions
9.17 Akaike's information criterion
9.18 Leverage
9.19 Misspecified model
9.20 Model checking in R
9.21 Extracting information from model objects
9.22 The summary tables for continuous and categorical explanatory variables
9.23 Contrasts
9.24 Model simplification by stepwise deletion
9.25 Comparison of the three kinds of contrasts
9.26 Aliasing
9.27 Orthogonal polynomial contrasts: contr.poly
9.28 Summary of statistical modelling
Chapter 10: Regression
10.1 Linear regression
10.2 Polynomial approximations to elementary functions
10.3 Polynomial regression
10.4 Fitting a mechanistic model to data
10.5 Linear regression after transformation
10.6 Prediction following regression
10.7 Testing for lack of fit in a regression
10.8 Bootstrap with regression
10.9 Jackknife with regression
10.10 Jackknife after bootstrap
10.11 Serial correlation in the residuals
10.12 Piecewise regression
10.13 Multiple regression
Chapter 11: Analysis of Variance
11.1 One-way ANOVA
11.2 Factorial experiments
11.3 Pseudoreplication: Nested designs and split plots
11.4 Variance components analysis
11.5 Effect sizes in ANOVA: aov or lm?
11.6 Multiple comparisons
11.7 Multivariate analysis of variance
Chapter 12: Analysis of Covariance
12.1 Analysis of covariance in R
12.2 ANCOVA and experimental design
12.3 ANCOVA with two factors and one continuous covariate
12.4 Contrasts and the parameters of ANCOVA models
12.5 Order matters in summary.aov
Chapter 13: Generalized Linear Models
13.1 Error structure
13.2 Linear predictor
13.3 Link function
13.4 Proportion data and binomial errors
13.5 Count data and Poisson errors
13.6 Deviance: Measuring the goodness of fit of a GLM
13.7 Quasi-likelihood
13.8 The quasi family of models
13.9 Generalized additive models
13.10 Offsets
13.11 Residuals
13.12 Overdispersion
13.13 Bootstrapping a GLM
13.14 Binomial GLM with ordered categorical variables
Chapter 14: Count Data
14.1 A regression with Poisson errors
14.2 Analysis of deviance with count data
14.3 Analysis of covariance with count data
14.4 Frequency distributions
14.5 Overdispersion in log-linear models
14.6 Negative binomial errors
Chapter 15: Count Data in Tables
15.1 A two-class table of counts
15.2 Sample size for count data
15.3 A four-class table of counts
15.4 Two-by-two contingency tables
15.5 Using log-linear models for simple contingency tables
15.6 The danger of contingency tables
15.7 Quasi-Poisson and negative binomial models compared
15.8 A contingency table of intermediate complexity
15.9 Schoener's lizards: A complex contingency table
15.10 Plot methods for contingency tables
15.11 Graphics for count data: Spine plots and spinograms
Chapter 16: Proportion Data
16.1 Analyses of data on one and two proportions
16.2 Count data on proportions
16.3 Odds
16.4 Overdispersion and hypothesis testing
16.5 Applications
16.6 Averaging proportions
16.7 Summary of modelling with proportion count data
16.8 Analysis of covariance with binomial data
16.9 Converting complex contingency tables to proportions
Chapter 17: Binary Response Variables
17.1 Incidence functions
17.2 Graphical tests of the fit of the logistic to data
17.3 ANCOVA with a binary response variable
17.4 Binary response with pseudoreplication
Chapter 18: Generalized Additive Models
18.1 Non-parametric smoothers
18.2 Generalized additive models
18.3 An example with strongly humped data
18.4 Generalized additive models with binary data
18.5 Three-dimensional graphic output from gam
Chapter 19: Mixed-Effects Models
19.1 Replication and pseudoreplication
19.2 The lme and lmer functions
19.3 Best linear unbiased predictors
19.4 Designed experiments with different spatial scales: Split plots
19.5 Hierarchical sampling and variance components analysis
19.6 Mixed-effects models with temporal pseudoreplication
19.7 Time series analysis in mixed-effects models
19.8 Random effects in designed experiments
19.9 Regression in mixed-effects models
19.10 Generalized linear mixed models
Chapter 20: Non-Linear Regression
20.1 Comparing Michaelis–Menten and asymptotic exponential
20.2 Generalized additive models
20.3 Grouped data for non-linear estimation
20.4 Non-linear time series models (temporal pseudoreplication)
20.5 Self-starting functions
20.6 Bootstrapping a family of non-linear regressions
Chapter 21: Meta-Analysis
21.1 Effect size
21.2 Weights
21.3 Fixed versus random effects
21.4 Random-effects meta-analysis of binary data
Chapter 22: Bayesian Statistics
22.1 Background
22.2 A continuous response variable
22.3 Normal prior and normal likelihood
22.4 Priors
22.5 Bayesian statistics for realistically complicated models
22.6 Practical considerations
22.7 Writing BUGS models
22.8 Packages in R for carrying out Bayesian analysis
22.9 Installing JAGS on your computer
22.10 Running JAGS in R
22.11 MCMC for a simple linear regression
22.12 MCMC for a model with temporal pseudoreplication
22.13 MCMC for a model with binomial errors
Chapter 23: Tree Models
23.1 Background
23.2 Regression trees
23.3 Using rpart to fit tree models
23.4 Tree models as regressions
23.5 Model simplification
23.6 Classification trees with categorical explanatory variables
23.7 Classification trees for replicated data
23.8 Testing for the existence of humps
Chapter 24: Time Series Analysis
24.1 Nicholson's blowflies
24.2 Moving average
24.3 Seasonal data
24.4 Built-in time series functions
24.5 Decompositions
24.6 Testing for a trend in the time series
24.7 Spectral analysis
24.8 Multiple time series
24.9 Simulated time series
24.10 Time series models
Chapter 25: Multivariate Statistics
25.1 Principal components analysis
25.2 Factor analysis
25.3 Cluster analysis
25.4 Hierarchical cluster analysis
25.5 Discriminant analysis
25.6 Neural networks
Chapter 26: Spatial Statistics
26.1 Point processes
26.2 Nearest neighbours
26.3 Tests for spatial randomness
26.4 Packages for spatial statistics
26.5 Geostatistical data
26.6 Regression models with spatially correlated errors: Generalized least squares
26.7 Creating a dot-distribution map from a relational database
Chapter 27: Survival Analysis
27.1 A Monte Carlo experiment
27.2 Background
27.3 The survivor function
27.4 The density function
27.5 The hazard function
27.6 The exponential distribution
27.7 Kaplan–Meier survival distributions
27.8 Age-specific hazard models
27.9 Survival analysis in R
27.10 Parametric analysis
27.11 Cox's proportional hazards
27.12 Models with censoring
Chapter 28: Simulation Models
28.1 Temporal dynamics: Chaotic dynamics in population size
28.2 Temporal and spatial dynamics: A simulated random walk in two dimensions
28.3 Spatial simulation models
28.4 Pattern generation resulting from dynamic interactions
Chapter 29: Changing the Look of Graphics
29.1 Graphs for publication
29.2 Colour
29.3 Cross-hatching
29.4 Grey scale
29.5 Coloured convex hulls and other polygons
29.6 Logarithmic axes
29.7 Different font families for text
29.8 Mathematical and other symbols on plots
29.9 Phase planes
29.10 Fat arrows
29.11 Three-dimensional plots
29.12 Complex 3D plots with wireframe
29.13 An alphabetical tour of the graphics parameters
29.14 Trellis graphics
References and Further Reading
Index
This edition first published 2013 © 2013 John Wiley & Sons, Ltd
Registered officeJohn Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex PO19 8SQ, United Kingdom
For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.
The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought.
Library of Congress Cataloging-in-Publication Data
Crawley, Michael J. The R book / Michael J. Crawley. – 2e. pages cm Includes bibliographical references and index. ISBN 978-0-470-97392-9 (hardback) 1. R (Computer program language) 2. Mathematical statistics–Data processing. I. Title. QA276.45.R3C73 2013 519.50285′5133–dc23 2012027339
A catalogue record for this book is available from the British Library.
ISBN: 978-0-470-97392-9
Preface
R is a high-level language and an environment for data analysis and graphics. The design of R was heavily influenced by two existing languages: Becker, Chambers and Wilks' S and Sussman's Scheme. The resulting language is very similar in appearance to S, but the underlying implementation and semantics are derived from Scheme. This book is intended as an introduction to the riches of the R environment, aimed at beginners and intermediate users in disciplines ranging from science to economics and from medicine to engineering. I hope that the book can be read as a text as well as dipped into as a reference manual. The early chapters assume absolutely no background in statistics or computing, but the later chapters assume that the material in the earlier chapters has been studied. The book covers data handling, graphics, mathematical functions, and a wide range of statistical techniques all the way from elementary classical tests, through regression and analysis of variance and generalized linear modelling, up to more specialized topics such as Bayesian analysis, spatial statistics, multivariate methods, tree models, mixed-effects models and time series analysis. The idea is to introduce users to the assumptions that lie behind the tests, fostering a critical approach to statistical modelling, but involving little or no statistical theory and assuming no background in mathematics or statistics.
Why should you switch to using R when you have mastered a perfectly adequate statistical package already? At one level, there is no point in switching. If you only carry out a very limited range of statistical tests, and you do not intend to do more (or different) in the future, then fine. The main reason for switching to R is to take advantage of its unrivalled coverage and the availability of new, cutting-edge applications in fields such as generalized mixed-effects modelling and generalized additive models. The next reason for learning R is that you want to be able to understand the literature. More and more people are reporting their results in the context of R, and it is important to know what they are talking about. Third, look around your discipline to see who else is using R: many of the top people will have switched to R already. A large proportion of the world's leading statisticians use R, and this should tell you something (many, indeed, contribute to R, as you can see below). Another reason for changing to R is the quality of back-up and support available. There is a superb network of dedicated R wizards out there on the web, eager to answer your questions. If you intend to invest sufficient effort to become good at statistical computing, then the structure of R and the ease with which you can write your own functions are major attractions. Last, and certainly not least, the product is free. This is some of the finest integrated software in the world, and yet it is yours for absolutely nothing.
Although much of the text will equally apply to S-PLUS, there are some substantial differences, so in order not to confuse things I concentrate on describing R. I have made no attempt to show where S-PLUS is different from R, but if you have to work in S-PLUS, then try it and see if it works.
Acknowledgements
S is an elegant, widely accepted, and enduring software system with outstanding conceptual integrity, thanks to the insight, taste, and effort of John Chambers. In 1998, the Association for Computing Machinery (ACM) presented him with its Software System Award, for ‘the S system, which has forever altered the way people analyze, visualize, and manipulate data’. R was inspired by the S environment that was developed by John Chambers, and which had substantial input from Douglas Bates, Rick Becker, Bill Cleveland, Trevor Hastie, Daryl Pregibon and Allan Wilks.
R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of the University of Auckland in New Zealand. Subsequently, a large group of individuals contributed to R by sending code and bug reports. John Chambers graciously contributed advice and encouragement in the early days of R, and later became a member of the core team. The current R is the result of a collaborative effort with contributions from all over the world.
Since mid-1997 there has been a core group with write access to the R source, currently consisting of Douglas Bates, John Chambers, Peter Dalgaard, Seth Falcon, Robert Gentleman, Kurt Hornik, Stefano Iacus, Ross Ihaka, Friedrich Leisch, Uwe Ligges, Thomas Lumley, Martin Maechler, Guido Masarotto (up to June 2003), Duncan Murdoch, Paul Murrell, Martyn Plummer, Brian Ripley, Deepayan Sarkar, Heiner Schwarte (up to October 1999), Duncan Temple Lang, Luke Tierney and Simon Urbanek.
R would not be what it is today without the invaluable help of the following people, who contributed by donating code, bug fixes and documentation: Valerio Aimale, Thomas Baier, Roger Bivand, Ben Bolker, David Brahm, Göran Broström, Patrick Burns, Vince Carey, Saikat DebRoy, Brian D'Urso, Lyndon Drake, Dirk Eddelbuettel, John Fox, Paul Gilbert, Torsten Hothorn, Robert King, Kjetil Kjernsmo, Philippe Lambert, Jan de Leeuw, Jim Lindsey, Patrick Lindsey, Catherine Loader, Gordon Maclean, John Maindonald, David Meyer, Jens Oehlschlägel, Steve Oncley, Richard O'Keefe, Hubert Palme, José C. Pinheiro, Anthony Rossini, Jonathan Rougier, Günther Sawitzki, Bill Simpson, Gordon Smyth, Adrian Trapletti, Terry Therneau, Bill Venables, Gregory R. Warnes, Andreas Weingessel, Morten Welinder, Simon Wood, and Achim Zeileis.
If you use R you should cite it in your written work. To cite the base package, put:
You can see the most up-to-date citation by typing citation() at the prompt. To cite individual contributed packages, you may find the appropriate citation in the description of the package, but failing that you will need to construct the citation from the author's name, date, and title of the package from the reference manual for the package that is available on CRAN (see p. 3).
Special thanks are due to the generations of graduate students on the annual GLIM course at Silwood. It was their feedback that enabled me to understand those aspects of R that are most difficult for beginners, and highlighted the concepts that require the most detailed explanation. Please tell me about the errors and omissions you find, and send suggestions for changes and additions to m.crawley@imperial.ac.uk.
The data files used in this book can be downloaded from http://www.bio.ic.ac.uk/research/mjcraw/therbook/index.htm.
M.J. Crawley AscotSeptember 2012
1
Getting Started
1.1 How to use this book
Try to put yourself in one of the following categories, then go to the appropriate category heading within this section to find some suggestions about how you might get best value from this book:
Beginner in both computing and statistics (Section 1.1.1);Student needing help with project work (1.1.2);Done some R and some statistics, but keen to learn more of both (1.1.3);Done regression and ANOVA, but want to learn more advanced statistical modelling (1.1.4);Experienced in statistics, but a beginner in R (1.1.5);Experienced in computing, but a beginner in R (1.1.6);Familiar with statistics and computing, but need a friendly reference manual (1.1.7).1.1.1 Beginner in both computing and statistics
The book is structured principally with you in mind. There are six key things to learn: how to arrange your data, how to read the data into R, how to check the data once within R, how to select the appropriate statistical model and apply it correctly, how to interpret the output, and how to present the analysis for publication. It is essential that you understand the basics thoroughly before trying to do the more complicated things, so study Chapters 3–6 carefully to begin with. Do all of the exercises that are illustrated in the text on your own computer. Now you need to do the hard part, which is selecting the right statistics to use. Model choice is extremely important, and is the thing that will develop most with experience. Do not by shy to ask for expert help with this. Never do an analysis that is more complicated than it needs to be, so start by reading about the classical tests to see if one of these fits your purposes (Chapter 8). Finally, try to understand the distinction between regression (Chapter 10) where the explanatory variable is continuous, and analysis of variance (Chapter 11), where the explanatory variable is categorical. One of these two is likely to be the most complicated method you will need.
1.1.2 Student needing help with project work
The first thing to ensure is that you know the difference between your response variable and your explanatory variable, and the distinction between a continuous variable and a categorical variable (Chapter 5). Once you have mastered this, then use the key at the beginning of Chapter 9 to see what kind of statistics you need to employ. It is most likely that if your response variable is a count, where you typically have lots of zeros, then you will want to use either the classical tests (Chapter 8) or count data in tables (Chapter 15). If your response variable is a continuous measure (e.g. a weight) then you will want to use either regression (Chapter 10) if your explanatory variable is continuous (e.g. an altitude) or analysis of variance (Chapter 11) if your explanatory variable is categorical (e.g. genotype). Do not forget to use the appropriate graphics (scatter plots for regressions, box and whisker plots for ANOVA).
1.1.3 Done some R and some statistics, but keen to learn more of both
The best plan is to skim quickly through the introductory material in case you have missed out on some of the basics. Certainly you should read all of the material in Chapter 2 on the fundamentals of the R language and Chapter 5 on graphics. Then, if you know what statistical models you want to use, go directly to the relevant chapter (e.g. regression in Chapter 10 and then non-linear regression in Chapter 20). Use the index for finding help on specific topics.
1.1.4 Done regression and ANOVA, but want to learn more advanced statistical modelling
If you learned regression and ANOVA in another language, the best plan is to go directly to Chapters 10–12 to see how the output from linear models is handled by R. Once you have familiarized yourself with data input (Chapter 3) and dataframes (Chapter 4), you should be able to go directly to the chapters on generalized linear models (Chapter 13), spatial statistics (Chapter 26), survival analysis (Chapter 27), non-linear models (Chapter 20) or mixed-effects models (Chapter 19) without any difficulty.
1.1.5 Experienced in statistics, but a beginner in R
The first thing is to get a thorough understanding of dataframes and data input to R, for which you should study Chapters 3 and 4. Then, if you know what statistics you want to do (e.g. mixed-effects models in R), you should be able to go straight to the appropriate material (Chapter 19 in this case). To understand the output from models in R, you will want to browse Chapter 9 on statistical modelling in R. Then you will want to present your data in the most effective way, by reading Chapter 5 on graphics and Chapter 29 on changing the look of graphics.
1.1.6 Experienced in computing, but a beginner in R
Well-written R code is highly intuitive and very readable. The most unfamiliar parts of R are likely to be the way it handles functions and the way it deals with environments. It is impossible to anticipate the order in which more advanced users are likely to encounter material and hence want to learn about specific features of the language, but vectorized calculations, subscripts on dataframes, function-writing and suchlike are bound to crop up early (Chapter 2). If you see a name in some code, and you want to find out about it, just type the name immediately after a question mark at the R prompt >. If, for example, you want know what rnbinom does, type:
?rnbinomRecognizing mathematical functions is quite straightforward because of their names and the fact that their arguments are enclosed in round brackets (). Subscripts on objects have square brackets [ ]. Multi-line blocks of R code are enclosed within curly brackets { }. Again, you may not be familiar with lists, or with applying functions to lists; elements within lists have double square brackets [[ ]].
Look at the sections at the head of Chapter 2 as a starting point. The index is probably your most sensible entry point for queries about specifics.
1.1.7 Familiar with statistics and computing, but need a friendly reference manual
If it is a topic you want to understand, then use the chapter list on pages v–vi and the Detailed Contents on pp. vii–xxi to find the most appropriate section. For aspects of the R language, look at the sections mentioned at the start of Chapter 2 on p. 12. You are likely to want to spend time browsing the contents of general material such as Chapter 5 on graphics and Chapter 29 on changing the look of graphics. Your best bet, in general, is likely to be to use the Index.
Get used to R's help pages. If you know the name of the function for which you require help, just type a question mark followed directly by the function name at R's screen prompt >. To find out what all the graphics parameters mean, for instance, just type:
?par1.2 Installing R
I assume that you have a PC or an Apple Mac, and that you want to install R on the hard disc. If you have access to the internet then this could hardly be simpler. First go to the site called CRAN (this stands for Comprehensive R Archive Network). You can type its full address,
http://cran.r-project.org/or simply type CRAN into Google and be transported effortlessly to the site. Once there, you need to ‘Download and Install R’ by running the appropriate precompiled binary distributions. Click to choose between Linux, Mac OS and Windows, then follow the (slightly different) instructions. You want the ‘base’ package and you want to run the setup program which will have a name like R*.exe (on a PC) or R*.dmg (on a Mac). When asked, say you want to ‘Run’ the file (rather than ‘Save’ it). Then just sit back and watch. If you do not have access to the internet, then get a friend to download R and copy it onto a memory stick for you.
1.3 Running R
To run R, just click on the R icon. If there is no icon, go to Programs, then to R, then click on the R icon. The first thing you see is the version number of R and the date of your version. It is a good idea to visit the CRAN site regularly to make sure that you have got the most up-to-date version of R. If you have an old version, it is best to uninstall your current version before downloading the new one.
The header explains that there is no warranty for this free software, and allows you to see the list of current contributors. Perhaps the most important information in the header is found under
citation()which shows how to cite the R software in your written work. The R Development Core Team has done a huge amount of work and we, the R user community, should give them due credit whenever we publish work that has used R.
Below the header you will see a blank line with a > symbol in the left-hand margin. This is called the prompt and is R's way of saying ‘What now?’. This is where you type in your commands, as introduced on p. 13. When working, you will sometimes see + at the left-hand side of the screen instead of >. This means that the last command you typed is incomplete. The commonest cause of this is that you have forgotten one or more brackets. If you can see what is missing (e.g. a final right-hand bracket) then just type the missing character and press enter, at which point the command will execute. If you have made a mistake, then press the Esc key and the command line prompt > will reappear. Then use the Up arrow key to retrieve your last command, at which point you can correct the mistake, using the Left and Right arrow keys.
1.4 The Comprehensive R Archive Network
CRAN is your first port of call for everything to do with R. It is from here that you download and install R, find contributed packages to solve particular problems, find the answers to frequently asked questions, read about the latest developments, get programming tips and much more besides. These are the current headings on the main website:
It is well worth browsing through The R Journal (formerly R News). This is the refereed journal of the R project for statistical computing. It features short to medium-length articles covering topics that might be of interest to users or developers of R, including:
Add-on packages – short introductions to or reviews of R extension packages.Programmer's Niche – hints for programming in R.Help Desk – hints for newcomers explaining aspects of R that might not be so obvious from reading the manuals and FAQs.Applications – demonstrating how a new or existing technique can be applied in an area of current interest using R, providing a fresh view of such analyses in R that is of benefit beyond the specific application.1.4.1 Manuals
There are several manuals available on CRAN:
An Introduction to R gives an introduction to the language and how to use R for doing statistical analysis and graphics.A draft of the R Language Definition, which documents the language per se – that is, the objects that it works on, and the details of the expression evaluation process, which are useful to know when programming R functions. This is perhaps the most important of all the manuals.Writing R Extensions covers how to create your own packages, write R help files, and use the foreign language (C, C++, Fortran, …) interfaces.R Data Import/Export describes the import and export facilities available either in R itself or via packages which are available from CRAN.R Installation and Administration, which is self-explanatory.R: A Language and Environment for Statistical Computing (referred to on the website as ‘The R Reference Index’) contains all the help files of the R standard and recommended packages in printable form.These manuals are also available in R itself by choosing Help/Manuals (in PDF) from the menu bar. There are also answers to Frequently Asked Questions (FAQs) and The R Journal, as mentioned above. The most useful part of the site, however, is the Search facility which allows you to investigate the contents of most of the R documents, functions, and searchable mail archives.
1.4.2 Frequently asked questions
R has three collections of answers to FAQs:
the R FAQ, which is the general collection and contains useful information for users on all platforms (Linux, Mac, Unix, Windows);the R Mac OS X FAQ for all users of Apple operating systems;the R Windows FAQ for all users of Microsoft operating systems.You need to read the first of these, plus the appropriate one for your platform.
1.4.3 Contributed documentation
This contains a wide range of longer (more than 100 pages) and shorter manuals, tutorials, and exercises provided by users of R. You should browse these to find the ones most relevant to your needs.
1.5 Getting help in R
The simplest way to get help in R is to click on the Help button on the toolbar of the RGui window (this stands for R's Graphic User Interface). Alternatively, if you are connected to the internet, you can type CRAN into Google and search for the help you need at CRAN (see Section 1.4). However, if you know the name of the function you want help with, you just type a question mark ? at the command line prompt followed by the name of the function. So to get help on read.table, just type
?read.tableSometimes you cannot remember the precise name of the function, but you know the subject on which you want help (e.g. data input in this case). Use the help.search function (without a question mark) with your query in double quotes like this:
help.search("data input")and (with any luck) you will see the names of the R functions associated with this query. Then you can use ?read.table to get detailed help.
Other useful functions are find and apropos. The find function tells you what package something is in:
find("lowess")[1] "package:stats"while apropos returns a character vector giving the names of all objects in the search list that match your (potentially partial) enquiry:
apropos("lm")1.5.1 Worked examples of functions
To see a worked example just type the function name (e.g. linear models, lm)
example(lm)and you will see the printed and graphical output produced by the lm function.
1.5.2 Demonstrations of R functions
These can be useful for seeing the range of things that R can do. Here are some for you to try:
demo(persp)demo(graphics)demo(Hershey)demo(plotmath)1.6 Packages in R
Finding your way around the contributed packages can be tricky, simply because there are so many of them, and the name of the package is not always as indicative of its function as you might hope. There is no comprehensive cross-referenced index, but there is a very helpful feature called ‘Task Views’ on CRAN, which explains the packages available under a limited number of usefully descriptive headings. Click on Packages on the CRAN home page, then inside Contributed Packages, you can click on CRAN Task Views, which allows you to browse bundles of packages assembled by topic. Currently, there are 29 Task Views on CRAN as follows:
BayesianBayesian InferenceChemPhysChemometrics and Computational PhysicsClinicalTrialsClinical Trial Design, Monitoring, and AnalysisClusterCluster Analysis & Finite Mixture ModelsDifferentialEquationsDifferential EquationsDistributionsProbability DistributionsEconometricsComputational EconometricsEnvironmetricsAnalysis of Ecological and Environmental DataExperimentalDesignDesign of Experiments (DoE) & Analysis of Experimental DataFinanceEmpirical FinanceGeneticsStatistical GeneticsGraphicsGraphic Displays & Dynamic Graphics & Graphic Devices & VisualizationHighPerformanceComputingHigh-Performance and Parallel Computing with RMachineLearningMachine Learning & Statistical LearningMedicalImagingMedical Image AnalysisMultivariateMultivariate StatisticsNaturalLanguageProcessingNatural Language ProcessingOfficialStatisticsOfficial Statistics & Survey MethodologyOptimizationOptimization and Mathematical ProgrammingPharmacokineticsAnalysis of Pharmacokinetic DataPhylogeneticsPhylogenetics, Especially Comparative MethodsPsychometricsPsychometric Models and MethodsReproducibleResearchReproducible ResearchRobustRobust Statistical MethodsSocialSciencesStatistics for the Social SciencesSpatialAnalysis of Spatial DataSurvivalSurvival AnalysisTimeSeriesTime Series AnalysisgRgRaphical Models in RClick on the Task View to get an annotated list of the packages available under any particular heading. With any luck you will find the package you are looking for.
To use one of the built-in libraries (listed in Table 1.1 ), simply type the library function with the name of the library in brackets. Thus, to load the spatial library type:
Table 1.1 Libraries used in this book that come supplied as part of the base package of R.
latticelattice graphics for panel plots or trellis graphsMASSpackage associated with Venables and Ripley's book entitled Modern Applied Statistics using S-PLUSmgcvgeneralized additive modelsnlmemixed-effects models (both linear and non-linear)nnetfeed-forward neural networks and multinomial log-linear modelsspatialfunctions for kriging and point pattern analysissurvivalsurvival analysis, including penalised likelihoodlibrary(spatial)1.6.1 Contents of packages
It is easy to use the help function to discover the contents of library packages. Here is how you find out about the contents of the spatial library:
library(help=spatial)Information on package "spatial"Package:spatialDescription:Functions for kriging and point pattern analysis.followed by a list of all the functions and data sets. You can view the full list of the contents of a library using objects with search() like this. Here are the contents of the spatial library:
objects(grep("spatial",search()))Then, to find out how to use, say, Ripley's K (Kfn), just type:
?Kfn1.6.2 Installing packages
The base package does not contain some of the libraries referred to in this book, but downloading these is very simple. Before you start, you should check whether you need to “Run as administrator” before you can install packages (right click on the R icon to find this). Run the R program, then from the command line use the install.packages function to download the libraries you want. You will be asked to highlight the mirror nearest to you for fast downloading (e.g. London), then everything else is automatic. The packages used in this book are
install.packages("akima")install.packages("boot")install.packages("car")install.packages("lme4")install.packages("meta")install.packages("mgcv")install.packages("nlme")install.packages("deSolve")install.packages("R2jags")install.packages("RColorBrewer")install.packages("RODBC")install.packages("rpart")install.packages("spatstat")install.packages("spdep")install.packages("tree")If you want other packages, then go to CRAN and browse the list called ‘Packages’ to select the ones you want to investigate.
1.7 Command line versus scripts
When writing functions and other multi-line sections of input you will find it useful to use a text editor rather than execute everything directly at the command line. Some people prefer to use R's own built-in editor. It is accessible from the RGui menu bar. Click on File then click on New script. At this point R will open a window entitled Untitled - R Editor. You can type and edit in this, then when you want to execute a line or group of lines, just highlight them and press Ctrl+R (the Control key and R together). The lines are automatically transferred to the command window and executed.
By pressing Ctrl+S you can save the contents of the R Editor window in a file that you will have to name. It will be given a .R file extension automatically. In a subsequent session you can click on File/Open script…when you will see all your saved .R files and can select the one you want to open.
Other people prefer to use an editor with more features. Tinn-R (“this is not notepad” for R) is very good, or you might like to try RStudio, which has the nice feature of allowing you to scroll back through all of the graphics produced in a session. These and others are free to download from the web.
1.8 Data editor
There is a data editor within R that can be accessed from the menu bar by selecting Edit/Data editor…. You provide the name of the matrix or dataframe containing the material you want to edit (this has to be a dataframe that is active in the current R session, rather than one which is stored on file), and a Data Editor window appears. Alternatively, you can do this from the command line using the fix function (e.g. fix(data.frame.name)). Suppose you want to edit the bacteria dataframe which is part of the MASS library:
library(MASS)attach(bacteria)fix(bacteria)The window has the look of a spreadsheet, and you can change the contents of the cells, navigating with the cursor or with the arrow keys. My preference is to do all of my data preparation and data editing in a spreadsheet before even thinking about using R. Once checked and edited, I save the data from the spreadsheet to a tab-delimited text file (*.txt) that can be imported to R very simply using the function called read.table (p. 20). One of the most persistent frustrations for beginners is that they cannot get their data imported into R. Things that typically go wrong at the data input stage and the necessary remedial actions are described on p. 139.
1.9 Changing the look of the R screen
The default settings of the command window are inoffensive to most people, but you can change them if you do not like them. The Rgui Configuration Editor under Edit/GUI preferences…is used to change the look of the screen. You can change the colour of the input line (default is red), the output line (default navy) or the background (default white). The default numbers of rows (25) and columns (80) can be changed, and you have control over the font (default Courier New) and font size (default 10).
1.10 Good housekeeping
To see what variables you have created in the current session, type:
objects()To see which packages and dataframes are currently attached:
search()At the end of a session in R, it is good practice to remove (rm) any variables names you have created (using, say, x <- 5.6) and to detach any dataframes you have attached earlier in the session. That way, variables with the same names but different properties will not get in each other's way in subsequent work:
rm(x,y,z)detach(worms)The detach command does not make the dataframe called worms disappear; it just means that the variables within worms, such as Slope and Area, are no longer accessible directly by name. To get rid of everything, including all the dataframes, type
rm(list=ls())but be absolutely sure that you really want to be as draconian as this before you execute the command.
1.11 Linking to other computer languages
Advanced users can employ the functions .C and .Fortran to provide a standard interface to compiled code that has been linked into R, either at build time or via dyn.load. They are primarily intended for compiled C and Fortran code respectively, but the .C function can be used with other languages which can generate C interfaces, for example C++. The .Internal and .Primitive interfaces are used to call C code compiled into R at build time. Functions .Call and .External provide interfaces which allow compiled code (primarily compiled C code) to manipulate R objects.
