R Data Analysis Cookbook Over 80 recipes to help you breeze through your data analysis projects using R Viswa Viswanathan Shanthi Viswanathan BIRMINGHAM - MUMBAI R Data Analysis Cookbook Copyright © 2015 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First published: May 2015 Production reference: 1220515 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78398-906-5 www.packtpub.com Credits Authors Viswa Viswanathan Project Coordinator Kinjal Bari Shanthi Viswanathan Proofreaders Reviewers Kenneth D Graves Safis Editing Stephen Copestake Jithin S L Dipanjan Sarkar Hang (Harvey) Yu Acquisition Editors Richard Brookes-Bland Richard Harvey Content Development Editor Samantha Gonsalves Technical Editor Anushree Arun Tendulkar Copy Editors Charlotte Carneiro Sameen Siddiqui Indexer Rekha Nair Graphics Sheetal Aute Abhinash Sahu Production Coordinator Manu Joseph Cover Work Manu Joseph About the Authors Viswa Viswanathan is an associate professor of Computing and Decision Sciences at the Stillman School of Business in Seton Hall University After completing his PhD in artificial intelligence, Viswa spent a decade in academia and then switched to a leadership position in the software industry for a decade During this period, he worked for Infosys, Igate, and Starbase He embraced academia once again in 2001 Viswa has taught extensively in fields ranging from operations research, computer science, software engineering, management information systems, and enterprise systems In addition to teaching at the university, Viswa has conducted training programs for industry professionals He has written several peer-reviewed research publications in journals such as Operations Research, IEEE Software, Computers and Industrial Engineering, and International Journal of Artificial Intelligence in Education He has authored a book titled Data Analytics with R: A hands-on approach Viswa thoroughly enjoys hands-on software development, and has single-handedly conceived, architected, developed, and deployed several web-based applications Apart from his deep interest in technical fields such as data analytics, artificial intelligence, computer science, and software engineering, Viswa harbors a deep interest in education, with special emphasis on the roots of learning and methods to foster deeper learning He has done research in this area and hopes to pursue the subject further Viswa would like to express deep gratitude to professors Amitava Bagchi and Anup Sen, who were inspirational forces during his early research career He is also grateful to several extremely intelligent colleagues, notable among them being Rajesh Venkatesh, Dan Richner, and Sriram Bala, who significantly shaped his thinking His aunt, Analdavalli; his sister, Sankari; and his wife, Shanthi, taught him much about hard work, and even the little he has absorbed has helped him immensely His sons, Nitin and Siddarth, have helped with numerous insightful comments on various topics Shanthi Viswanathan is an experienced technologist who has delivered technology management and enterprise architecture consulting to many enterprise customers She has worked for Infosys Technologies, Oracle Corporation, and Accenture As a consultant, Shanthi has helped several large organizations, such as Canon, Cisco, Celgene, Amway, Time Warner Cable, and GE among others, in areas such as data architecture and analytics, master data management, service-oriented architecture, business process management, and modeling When she is not in front of her Mac, Shanthi spends time hiking in the suburbs of NY/NJ, working in the garden, and teaching yoga Shanthi would like to thank her husband, Viswa, for all the great discussions on numerous topics during their hikes together and for exposing her to R and Java She would also like to thank her sons, Nitin and Siddarth, for getting her into the data analytics world About the Reviewers Kenneth D Graves believes that data science will give us superpowers Or, at the very least, allow us to make better decisions Toward this end, he has over 15 years of experience in data science and technology, specializing in machine learning, big data, signal processing and marketing, and social media analytics He has worked for Fortune 500 companies such as CBS and RCA-Technicolor, as well as finance and technology companies, designing state-of-art technologies and data solutions to improve business and organizational decision-making processes and outcomes His projects have included facial and brand recognition, natural language processing, and predictive analytics He works and mentors others in many technologies, including R, Python, C++, Hadoop, and SQL Kenneth holds degrees and/or certifications in data science, business, film, and classical languages When he is not trying to discover superpowers, he is a data scientist and acting CTO at Soshag, LLC., a social media analytics firm He is available for consulting and data science projects throughout the Greater Boston Area He currently lives in Wellesley, MA I wish to thank my wife, Jill, for being the inspiration for all that I Jithin S L completed his BTech in information technology from Loyola Institute of Technology and Science He started his career in the field of analytics and then moved to various verticals of big data technology He has worked with reputed organizations, such as Thomson Reuters, IBM, and Flytxt, in different roles He has worked in the banking, energy, healthcare, and telecom domains, and has handled global projects on big data technology He has submitted many research papers on technology and business at national and international conferences Currently, Jithin is associated with IBM Corporation as a systems analyst—big data big insight in business analytics and optimization unit “Change is something which brings us to THINK beyond our limits, worries it also provides an opportunity to learn new things in a new way, experiment, explore, and advise towards success.” -Jithin I surrender myself to God almighty who helped me review this book in an effective way I dedicate my work on this book to my dad, Mr N Subbian Asari; my lovable mom, Mrs M Lekshmi; and my sweet sister, Ms S.L Jishma, for coordinating and encouraging me to review this book Last but not least, I would like to thank all my friends Dipanjan Sarkar is an IT engineer at Intel, the world's largest silicon company, where he works on analytics and enterprise application development As part of his experience in the industry so far, he has previously worked as a data engineer at DataWeave, one of India's emerging big data analytics start-ups and also as a graduate technical intern in Intel Dipanjan received his master's degree in information technology from the International Institute of Information Technology, Bengaluru His interests include learning about new technology, disruptive start-ups, and data science He has also reviewed Learning R for Geospatial Analysis, Packt Publishing Hang (Harvey) Yu graduated from the University of Illinois at Urbana-Champaign with a PhD in computational biophysics and a master's degree in statistics He has extensive experience on data mining, machine learning, and statistics In the past, Harvey has worked on areas such as stochastic simulations and time series (in C and Python) as part of his academic work He was intrigued by algorithms and mathematical modeling He has been involved in data analytics since then He is currently working as a data scientist in Silicon Valley He is passionate about data sciences He has developed statistical/mathematical models based on techniques such as optimization and predictive modeling in R Previously, Harvey worked as a computational sciences intern for ExxonMobil When Harvey is not programming, he is playing soccer, reading fiction books, or listening to classical music You can get in touch with him at hangyu1@illinois.edu or on LinkedIn at www.linkedin.com/in/hangyu1 www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library Here, you can search, access, and read Packt's entire library of books Why Subscribe? ff Fully searchable across every book published by Packt ff Copy and paste, print, and bookmark content ff On demand and accessible via a web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view entirely free books Simply use your login credentials for immediate access Table of Contents Preface v Chapter 1: Acquire and Prepare the Ingredients – Your Data Introduction 2 Reading data from CSV files Reading XML data Reading JSON data Reading data from fixed-width formatted files Reading data from R files and R libraries Removing cases with missing values 11 Replacing missing values with the mean 13 Removing duplicate cases 15 Rescaling a variable to [0,1] 16 Normalizing or standardizing data in a data frame 18 Binning numerical data 20 Creating dummies for categorical variables 22 Chapter 2: What's in There? – Exploratory Data Analysis 25 Introduction Creating standard data summaries Extracting a subset of a dataset Splitting a dataset Creating random data partitions Generating standard plots such as histograms, boxplots, and scatterplots Generating multiple plots on a grid Selecting a graphics device Creating plots with the lattice package Creating plots with the ggplot2 package Creating charts that facilitate comparisons Creating charts that help to visualize possible causality 26 26 28 31 32 35 43 45 46 49 55 60 i Chapter 11 There's more The database-specific packages provide a lot of functionality, and pretty much most of what can be done within a SQL client can also be done from within an R environment We show a few examples as follows Fetching all rows The following command is used to fetch all rows: > fetch(rs,n=-1) Use n=-1 to fetch all rows When the SQL query is long When the SQL query is long, it becomes unwieldy to specify the whole query as one long string spanning several lines Use the paste() function to break the query over multiple lines and make it more readable: > dbSendQuery(con, statement=paste( "select ordernumber, orderdate, customername", "from orders o, customers c", "where o.customer = c.customer", "and c.state = 'NJ'", "ORDER BY ordernumber")) Note the use of the single quotes to specify a string literal Reading data from NoSQL databases – MongoDB Unlike relational databases for which a somewhat standard approach works across all relational databases, the fluid state of NoSQL databases means that no such standard approach has yet evolved We illustrate this with MongoDB using the rmongodb package 307 Playing Nice – Connecting to Other Systems Getting ready Prepare the environment by following these steps: Download and install MongoDB Start mongod as a background process and then start mongo Create a new database customer and a collection called orders: > use customer > db.orders.save({customername:"John", orderdate:ISODate("2014-11-01"),orderamount:1000}) > db.orders.find() > db.save How to it To read data from MongoDB, follow these steps: Install the rmongodb package and create a connection: > > > > > install.packages("rmongodb") library(rmongodb) mongo coll json dat