Transcription of The Art of R Programming
1 TA ME YOUR DATA. THE. ART OF R. T H E A R T OF R PROG R A MMING. PROGR A MMING. R is the world's most popular language for developing Interface R with C/C++ and Python for increased statistical software: Archaeologists use it to track the speed or functionality spread of ancient civilizations, drug companies use it Find new packages for text analysis, image manipula- to discover which medications are safe and effective, tion, and thousands more and actuaries use it to assess financial risks and keep A TOUR O F S TAT I S T I C A L S O F T W A R E D E S I G N. markets running smoothly. Squash annoying bugs with advanced debugging techniques The Art of R Programming takes you on a guided tour of software development with R, from basic types Whether you're designing aircraft, forecasting the and data structures to advanced topics like closures, weather, or you just need to tame your data, The Art of NORMAN MATLOFF.
2 Recursion, and anonymous functions. No statistical R Programming is your guide to harnessing the power knowledge is required, and your Programming skills of statistical computing. can range from hobbyist to pro. ABOUT THE AUTHOR. Along the way, you'll learn about functional and object- Norman Matloff is a professor of computer science oriented Programming , running mathematical simulations, (and a former professor of statistics) at the University and rearranging complex data into simpler, more useful of California, Davis. His research interests include formats. You'll also learn to: parallel processing and statistical regression, and Create artful graphs to visualize complex data sets he is the author of several widely used web tutorials and functions on software development.
3 He has written articles for the New York Times, the Washington Post, Forbes Write more efficient code using parallel R and Magazine, and the Los Angeles Times, and he is the vectorization co-author of The Art of Debugging (No Starch Press). T H E F I N E ST I N G E E K E N T E RTA I N M E N T . w w M ATLOFF. I L I E F L AT . $ ($ CDN). This book uses RepKover a durable binding that won't snap shut. STATISTICAL SOFTWARE. COMPUTERS/MATHEMATICAL &. SHELVE IN: FSC LOGO. THE ART OF R. Programming . THE ART OF R. Programming . A Tour of Statistical Software Design by Norman Matloff San Francisco THE ART OF R Programming . Copyright 2011 by Norman Matloff. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
4 15 14 13 12 11 123456789. ISBN-10: 1-59327-384-3. ISBN-13: 978-1-59327-384-2. Publisher: William Pollock Production Editor: Alison Law Cover and Interior Design: Octopod Studios Developmental Editor: Keith Fancher Technical Reviewer: Hadley Wickham Copyeditor: Marilyn Smith Compositors: Alison Law and Serena Yang Proofreader: Paula L. Fleming Indexer: BIM Indexing & Proofreading Services For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 38 Ringold Street, San Francisco, CA 94103. phone: ; fax: ; Library of Congress Cataloging-in-Publication Data Matloff, Norman S. The art of R Programming : tour of statistical software design / by Norman Matloff.
5 P. cm. ISBN-13: 978-1-59327-384-2. ISBN-10: 1-59327-384-3. 1. Statistics-Data processing. 2. R (Computer program language) I. Title. 2011. '5133-dc23. 2011025598. No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the bene t of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an As Is basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc.
6 Shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the infor- mation contained in it. BRIEF CONTENTS. Acknowledgments .. xvii Introduction .. xix Chapter 1: Getting Started .. 1. Chapter 2: Vectors .. 25. Chapter 3: Matrices and Arrays .. 59. Chapter 4: Lists.. 85. Chapter 5: Data Frames ..101. Chapter 6: Factors and Tables ..121. Chapter 7: R Programming Structures ..139. Chapter 8: Doing Math and Simulations in R ..189. Chapter 9: Object-Oriented Programming ..207. Chapter 10: Input/Output ..231. Chapter 11: String Manipulation ..251. Chapter 12: Graphics ..261. Chapter 13: Debugging ..285. Chapter 14: Performance Enhancement: Speed and Memory.
7 305. Chapter 15: Interfacing R to Other Languages ..323. Chapter 16: Parallel R ..333. Appendix A: Installing R ..353. Appendix B: Installing and Using Packages ..355. CONTENTS IN DETAIL. ACKNOWLEDGMENTS xvii INTRODUCTION xix Why Use R for Your Statistical Work? .. xix Object-Oriented Programming .. xvii Functional Programming .. xvii Whom Is This Book For? .. xviii My Own Background .. xix 1. GETTING STARTED 1. How to Run R .. 1. Interactive Mode .. 2. Batch Mode .. 3. A First R Session .. 4. Introduction to Functions .. 7. Variable Scope .. 9. Default Arguments .. 9. Preview of Some Important R Data Structures .. 10. Vectors, the R Workhorse .. 10. Character Strings .. 11. Matrices .. 11. Lists.
8 12. Data Frames .. 14. Classes .. 15. Extended Example: Regression Analysis of Exam Grades .. 16. Startup and Shutdown .. 19. Getting Help .. 20. The help() Function .. 20. The example() Function .. 21. If You Don't Know Quite What You're Looking For .. 22. Help for Other Topics .. 23. Help for Batch Mode .. 24. Help on the Internet .. 24. 2. VECTORS 25. Scalars, Vectors, Arrays, and Matrices .. 26. Adding and Deleting Vector Elements .. 26. Obtaining the Length of a Vector .. 27. Matrices and Arrays as Vectors .. 28. Declarations .. 28. Recycling .. 29. Common Vector Operations .. 30. Vector Arithmetic and Logical Operations .. 30. Vector Indexing .. 31. Generating Useful Vectors with the : Operator.
9 32. Generating Vector Sequences with seq() .. 33. Repeating Vector Constants with rep() .. 34. Using all() and any() .. 35. Extended Example: Finding Runs of Consecutive Ones .. 35. Extended Example: Predicting Discrete-Valued Time Series .. 37. Vectorized Operations .. 39. Vector In, Vector Out .. 40. Vector In, Matrix Out .. 42. NA and NULL Values .. 43. Using NA .. 43. Using NULL .. 44. Filtering .. 45. Generating Filtering Indices .. 45. Filtering with the subset() Function .. 47. The Selection Function which() .. 47. A Vectorized if-then-else: The ifelse() Function .. 48. Extended Example: A Measure of Association .. 49. Extended Example: Recoding an Abalone Data Set .. 51. Testing Vector Equality.
10 54. Vector Element Names .. 56. More on c() .. 56. 3. MATRICES AND ARRAYS 59. Creating Matrices .. 59. General Matrix Operations .. 61. Performing Linear Algebra Operations on Matrices .. 61. Matrix Indexing .. 62. Extended Example: Image Manipulation .. 63. Filtering on Matrices .. 66. Extended Example: Generating a Covariance Matrix .. 69. viii Contents in Detail Applying Functions to Matrix Rows and Columns .. 70. Using the apply() Function .. 70. Extended Example: Finding Outliers .. 72. Adding and Deleting Matrix Rows and Columns .. 73. Changing the Size of a Matrix .. 73. Extended Example: Finding the Closest Pair of Vertices in a Graph .. 75. More on the Vector/Matrix Distinction .. 78.