By Andrie De Vries And - Free Download PDF

12d ago
5.39 MB
435 Pages

R2nd Editionby Andrie de Vries andJoris Meys

R For Dummies , 2nd EditionPublished by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030‐5774, www.wiley.comCopyright 2015 by John Wiley & Sons, Inc., Hoboken, New JerseyMedia and software compilation copyright 2015 by John Wiley & Sons, Inc. All rights reserved.Published simultaneously in CanadaNo part of this publication may be reproduced, stored in a retrieval system or transmitted in any form orby any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the PermissionsDepartment, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748‐6011, fax (201)748‐6008, or online at Wiley, For Dummies, the Dummies Man logo,, Making Everything Easier, andrelated trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not beused without written permission. All trademarks are the property of their respective owners. John Wiley &Sons, Inc. is not associated with any product or vendor mentioned in this book.LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OFTHE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDINGWITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTYMAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE ANDSTRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK ISSOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL,ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED,THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THEPUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACTTHAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR APOTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THEPUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE ORRECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNETWEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THISWORK WAS WRITTEN AND WHEN IT IS READ.For general information on our other products and services, please contact our Customer Care Departmentwithin the U.S. at 877‐762‐2974, outside the U.S. at 317‐572‐3993, or fax 317‐572‐4002. For technical support,please visit publishes in a variety of print and electronic formats and by print‐on‐demand. Some materialincluded with standard print versions of this book may not be included in e‐books or in print‐on‐demand.If this book refers to media such as a CD or DVD that is not included in the version you purchased, youmay download this material at For more information about Wileyproducts, visit of Congress Control Number: 2015941928ISBN 978‐1‐119‐05580‐8 (pbk); ISBN 978‐1‐119‐05583‐9 (epub); 978‐1‐119‐05585‐3 (epdf)Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1

Table of ContentsIntroduction. 1About This Book. 1Changes in the Second Edition. 2Conventions Used in This Book. 3What You’re Not to Read. 4Foolish Assumptions. 4How This Book Is Organized. 5Part I: Getting Started with R Programming. 5Part II: Getting Down to Work in R. 5Part III: Coding in R. 5Part IV: Making the Data Talk. 5Part V: Working with Graphics. 6Part VI: The Part of Tens. 6Icons Used in This Book. 6Beyond the Book. 7Where to Go from Here. 7Part I: Getting Started with R Programming. 9Chapter 1: Introducing R: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . 11Recognizing the Benefits of Using R. 12It comes as free, open‐source code. 12It runs anywhere. 13It supports extensions. 13It provides an engaged community. 13It connects with other languages. 14Looking At Some of the Unique Features of R. 15Performing multiple calculations with vectors. 15Processing more than just statistics. 16Running code without a compiler. 16Chapter 2: Exploring R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Working with a Code Editor. 20Exploring RGui. 21Dressing up with RStudio. 23Starting Your First R Session. 25Saying hello to the world. 25Doing simple math. 26Using vectors. 26

ivR For Dummies Storing and calculating values. 27Talking back to the user. 28Sourcing a Script. 29Echoing your work. 30Navigating the Environment. 32Manipulating the content of the environment. 32Saving your work. 33Retrieving your work. 34Chapter 3: The Fundamentals of R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Using the Full Power of Functions. 35Vectorizing your functions. 36Putting the argument in a function. 37Making history. 39Keeping Your Code Readable. 40Following naming conventions. 40Structuring your code. 43Adding comments. 45Getting from Base R to More. 45Finding packages. 45Installing packages. 46Loading and unloading packages. 46Part II: Getting Down to Work in R. 49Chapter 4: Getting Started with Arithmetic . . . . . . . . . . . . . . . . . . . . . . 51Working with Numbers, Infinity, and Missing Values. 51Doing basic arithmetic. 52Using mathematical functions. 54Calculating whole vectors. 57To infinity and beyond. 58Organizing Data in Vectors. 60Discovering the properties of vectors. 61Creating vectors. 63Combining vectors. 64Repeating vectors. 64Getting Values in and out of Vectors. 65Understanding indexing in R. 65Extracting values from a vector. 66Changing values in a vector. 67Working with Logical Vectors. 68Comparing values. 69Using logical vectors as indices. 70

Table of Contents Combining logical statements. 71Summarizing logical vectors. 72Powering Up Your Math. 73Using arithmetic vector operations. 73Recycling arguments. 76Chapter 5: Getting Started with Reading and Writing . . . . . . . . . . . . . 79Using Character Vectors for Text Data. 79Assigning a value to a character vector. 80Creating a character vector with more than one element. 80Extracting a subset of a vector. 81Naming the values in your vectors. 82Manipulating Text. 84String theory: Combining and splitting strings. 84Sorting text. 88Finding text inside text. 89Substituting text. 91Revving up with regular expressions. 92Factoring in Factors. 94Creating a factor. 95Converting a factor. 96Looking at levels. 98Distinguishing data types. 99Working with ordered factors. 100Chapter 6: Going on a Date with R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Working with Dates. 104Presenting Dates in Different Formats. 106Adding Time Information to Dates. 107Formatting Dates and Times. 109Performing Operations on Dates and Times. 109Addition and subtraction. 109Comparison of dates. 110Extraction. 111Chapter 7: Working in More Dimensions . . . . . . . . . . . . . . . . . . . . . . . 113Adding a Second Dimension. 113Discovering a new dimension. 114Combining vectors into a matrix. 117Using the Indices. 118Extracting values from a matrix. 118Replacing values in a matrix. 120Naming Matrix Rows and Columns. 121Changing the row and column names. 122Using names as indices. 123v

viR For Dummies Calculating with Matrices. 123Using standard operations with matrices. 124Calculating row and column summaries. 125Doing matrix arithmetic. 126Adding More Dimensions. 127Creating an array. 128Using dimensions to extract values. 129Combining Different Types of Values in a Data Frame. 130Creating a data frame from a matrix. 130Creating a data frame from scratch. 132Naming variables and observations. 133Manipulating Values in a Data Frame. 134Extracting variables, observations, and values. 135Adding observations to a data frame. 136Adding variables to a data frame. 139Combining Different Objects in a List. 140Creating a list. 141Extracting components from lists. 142Changing the components in lists. 144Reading the output of str( ) for lists. 146Seeing the forest through the trees. 148Part III: Coding in R. 149Chapter 8: Putting the Fun in Functions . . . . . . . . . . . . . . . . . . . . . . . . . 151Moving from Scripts to Functions. 151Making the script. 152Transforming the script. 153Using the function. 154Reducing the number of lines. 155Using Arguments the Smart Way. 157Adding more arguments. 157Conjuring tricks with dots. 159Using functions as arguments. 161Coping with Scoping. 163Crossing the borders. 164Dispatching to a Method. 165Finding the methods behind the function. 166Doing it yourself. 168Chapter 9: Controlling the Logical Flow . . . . . . . . . . . . . . . . . . . . . . . . 171Making Choices with if Statements. 172Doing Something Else with an if. . .else Statement. 174

Table of Contents Vectorizing Choices. 176Looking at the problem. 176Choosing based on a logical vector. 176Making Multiple Choices. 178Chaining if. . .else statements. 178Switching between possibilities. 180Looping Through Values. 181Constructing a for loop. 181Calculating values in a for loop. 182Looping without Loops: Meeting the Apply Family. 184Looking at the family features. 185Meeting three of the members. 185Applying functions on rows and columns.

viii R or Dummies Part IV: Making the Data Talk..... 219 Chapter 12: Getting Data into and out of R . . . . . . . . . . . . . . . . . . . . . . .221