Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
R Programming By Example
R Programming By Example

R Programming By Example: Practical, hands-on projects to help you get started with R

Arrow left icon
Profile Icon Omar Trejo Navarro Profile Icon Trejo Navarro
Arrow right icon
€22.99 €32.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (4 Ratings)
eBook Dec 2017 470 pages 1st Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Omar Trejo Navarro Profile Icon Trejo Navarro
Arrow right icon
€22.99 €32.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (4 Ratings)
eBook Dec 2017 470 pages 1st Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

R Programming By Example

Understanding Votes with Descriptive Statistics

This chapter shows how to perform a descriptive statistics analysis to get a general idea about the data we're dealing with, which is usually the first step in data analysis projects and is a basic ability for data analysts in general. We will learn how to clean and transform data, summarize data in a useful way, find specific observations, create various kinds of plots that provide intuition for the data, use correlations to understand relations among numerical variables, use principal components to find optimal variable combinations, and put everything together into code that is reusable, understandable, and easily modifiable.

Since this is a book about programming with R and not about doing statistics with R, our focus will be on the programming side of things, not the statistical side. Keep that in mind while reading it...

This chapter's required packages

During this chapter we will make use of the following R packages. If you don't already have them installed, you can look into Appendix, Required Packages for instructions on how do so.

Package

Used for

ggplot2

High-quality graphs

viridis

Color palette for graphs

corrplot

Correlation plots

ggbiplot

Principal components plots

progress

Show progress for iterations

The Brexit votes example

In June 2016, a referendum was held in the United Kingdom (UK) to decide whether or not to remain part of the European Union (EU). 72% of registered voters took part, and of those, 51.2% voted to leave the EU. In February 2017, Martin Rosenbaum, freedom of information specialist at BBC News, published the article, Local Voting Figures Shed New Light on EU Referendum (http://www.bbc.co.uk/news/uk-politics-38762034). He obtained data from 1,070 electoral wards (the smallest administrative division for electoral purposes in the UK), with numbers for Leave and Remain votes in each ward.

Martin Rosenbaum calculated some statistical associations between the proportion of Leave votes in a ward and some of its social, economic, and demographic characteristics by making use of the most recent UK census, which was conducted in 2011. He used his data for a university...

Cleaning and setting up the data

Setting up the data for this example is straightforward. We will load the data, correctly label missing values, and create some new variables for our analysis. Before we start, make sure the data.csv file is in the same directory as the code you're working with, and that your working directory is properly setup. If you don't know how to do so, setting up your working directory is quite easy, you simply call the setwd() function passing the directory you want to use as such. For example, setwd(/home/user/examples/) would use the /home/user/examples directory to look for files, and save files to.

If you don’t know how to do so, setting up your working directory is quite easy, you simply call the setwd() function passing the directory you want to use as such. For example, setwd(/home/user/examples/) would use the /home/user/examples...

Summarizing the data into a data frame

To get a summary of the data, we may execute summary(data) and see the relevant summaries for each type of variable. The summary is tailored for each column's data type. As you can see, numerical variables such as ID and NVotes get a quantile summary, while factor (categorical) variables get a count for each different category, such as AreaType and RegionName. If there are many categories, the summary will show the categories that appear the most and group the rest into a (Other) group, as we can see at the bottom of RegionName.

summary(data)
#> ID RegionName NVotes Leave
#> Min. : 1 Length: 1070 Min. : 1039 Min. : 287
#> 1st Qu.: 268 Class : character 1st Qu.: 4252 1st Qu.: 1698
#> Median : 536 Mode : character Median : 5746 Median : 2874
#> Mean : 536...

Getting intuition with graphs and correlations

Now that we have some clean data to work with, we will create lots of plots to build intuition about the data. In this chapter, we will work with plots that are easy to create and are used for exploratory purposes. In Chapter 4, Simulating Sales Data and Working with Databases, we will look into publication ready plots that are a little more verbose to create.

Visualizing variable distributions

Our first plot is a simple one and shows the proportion of votes by each RegionName. As you can see in the plot shown below, the London, North West, and West Midlands regions account for around 55 percent of the observations in the data.

Vote Proportion by Region

To create the plot, we...

Creating a new dataset with what we've learned

What we have learned so far in this chapter is that age, education, and ethnicity are important factors in understanding the way people voted in the Brexit Referendum. Younger people with higher education levels are related with votes in favor of remaining in the EU. Older white people are related with votes in favor of leaving the EU. We can now use this knowledge to make a more succinct data set that incorporates this knowledge. First we add relevant variables, and then we remove non-relevant variables.

Our new relevant variables are two groups of age (adults below and above 45), two groups of ethnicity (whites and non-whites), and two groups of education (high and low education levels):

data$Age_18to44 <- (
    data$Age_18to19 +
    data$Age_20to24 +
    data$Age_25to29 +
    data$Age_30to44
)
data$Age_45plus <- (
 ...

Building new variables with principal components

Principal Component Analysis (PCA) is a dimensionality reduction technique that is widely used in data analysis when there are many numerical variables, some of which may be correlated, and we would like to reduce the number of dimensions required to understand the data.

It can be useful to help us understand the data, since thinking in more than three dimensions can be problematic, and to accelerate algorithms that are computationally intensive, especially with large numbers of variables. With PCA, we can extract most of the information into only one or two variables constructed in a very specific way, such that they capture the most variance while having the added benefit of being uncorrelated among them by construction.

The first principal component is a linear combination of the original variables which captures the maximum...

Putting it all together into high-quality code

Now that we have the fundamentals about analyzing data with descriptive statistics, we're going to improve our code's structure and flexibility by breaking it up into functions. Even though this is common knowledge among efficient programmers, it's not a common practice among data analysts. Many data analysts would simply paste the code we have developed all together, as-is, into a single file, and run it every time they wanted to perform the analysis. We won't be adding new features to the analysis. All we'll do is reorder code into functions to encapsulate their inner-workings and communicate intention with function names (this substantially reduces the need for comments).

We'll focus on producing high-quality code that is easy to read, reuse, modify, and fix (in case of bugs). The way we actually do...

Summary

This chapter showed how to perform a qualitative analysis that is useful as a first step when doing data analysis. We showed some descriptive statistics techniques and how to implement them programmatically. With these skills, we are able to perform simple yet powerful analyses and save the results for later use. Specifically, we showed how to do basic data cleaning, how to create graphs programmatically, how to create matrix scatter plots and matrix correlations, how to perform Principal Component Analysis, and how to combine these tools to understand the data at hand. Finally, we touched on the basics of high-quality code and showed how to transform your initial data analysis code into programs that are modular, flexible, and easy to work with.

In Chapter 3, Predicting Votes with Linear Models, we'll show how to extend the current analysis with qualitative tools...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get a firm hold on the fundamentals of R through practical hands-on examples
  • Get started with good R programming fundamentals for data science
  • Exploit the different libraries of R to build interesting applications in R

Description

R is a high-level statistical language and is widely used among statisticians and data miners to develop analytical applications. Often, data analysis people with great analytical skills lack solid programming knowledge and are unfamiliar with the correct ways to use R. Based on the version 3.4, this book will help you develop strong fundamentals when working with R by taking you through a series of full representative examples, giving you a holistic view of R. We begin with the basic installation and configuration of the R environment. As you progress through the exercises, you'll become thoroughly acquainted with R's features and its packages. With this book, you will learn about the basic concepts of R programming, work efficiently with graphs, create publication-ready and interactive 3D graphs, and gain a better understanding of the data at hand. The detailed step-by-step instructions will enable you to get a clean set of data, produce good visualizations, and create reports for the results. It also teaches you various methods to perform code profiling and performance enhancement with good programming practices, delegation, and parallelization. By the end of this book, you will know how to efficiently work with data, create quality visualizations and reports, and develop code that is modular, expressive, and maintainable.

Who is this book for?

This books is for aspiring data science professionals or statisticians who would like to learn about the R programming language in a practical manner. Basic programming knowledge is assumed.

What you will learn

  • Discover techniques to leverage R's features, and work with packages
  • Perform a descriptive analysis and work with statistical models using R
  • Work efficiently with objects without using loops
  • Create diverse visualizations to gain better understanding of the data
  • Understand ways to produce good visualizations and create reports for the results
  • Read and write data from relational databases and REST APIs, both packaged and unpackaged
  • Improve performance by writing better code, delegating that code to a more efficient programming language, or making it parallel

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 22, 2017
Length: 470 pages
Edition : 1st
Language : English
ISBN-13 : 9781788291361
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Dec 22, 2017
Length: 470 pages
Edition : 1st
Language : English
ISBN-13 : 9781788291361
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
R Data Mining
€36.99
R Programming By Example
€41.99
Modern R Programming Cookbook
€36.99
Total 115.97 Stars icon

Table of Contents

11 Chapters
Introduction to R Chevron down icon Chevron up icon
Understanding Votes with Descriptive Statistics Chevron down icon Chevron up icon
Predicting Votes with Linear Models Chevron down icon Chevron up icon
Simulating Sales Data and Working with Databases Chevron down icon Chevron up icon
Communicating Sales with Visualizations Chevron down icon Chevron up icon
Understanding Reviews with Text Analysis Chevron down icon Chevron up icon
Developing Automatic Presentations Chevron down icon Chevron up icon
Object-Oriented System to Track Cryptocurrencies Chevron down icon Chevron up icon
Implementing an Efficient Simple Moving Average Chevron down icon Chevron up icon
Adding Interactivity with Dashboards Chevron down icon Chevron up icon
Required Packages Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(4 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 0%
1 star 50%
John Beck Aug 29, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great content and very well explained. At first I was hesitating about buying it because of the other comment here, but I had heard good things about the book so I bought it, and I’m glad I did. Never had a problem with the data files or source code files. Easy to download and follow, and great material. Thanks! Definitely recommended.
Amazon Verified review Amazon
John Stewart Sep 06, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I know programming at an intermediate level, and I've recently started to focus in Data Science. This book was the right one for me! It does a great job at introducing R from a programmer's perspective, not only showing you how to do interesting Data Science projects, but actually explaining the underlying programming concepts which I had not seen well explained in other R books. Thanks!
Amazon Verified review Amazon
S N Jul 10, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Pros:-The book seems to have practical, detailed examples and quality instruction.Major Con:-The data files required to use the book are NOT available. The author only provides links to Git Hub "pointer files", which have to be downloaded via a separate command prompt utility (Git LFS). The author provides vague, incorrect instructions for how to download the files. You will need to spend several hours researching and troubleshooting just to figure out how to correctly run the utility and which commands to run. What's worse: once you get the utility commands to successfully execute, you'll get an error message indicating that the .csv files are not available on the server.-The publisher and author REFUSE to provide accessible links to the .csv files, or correct/detailed instructions for how to retrieve them. If you contact the publisher or author, the author will ignore your feedback about error messages and will simply copy/paste vague instructions from Errata which he posted previously on the publisher's website (i.e. indicating that previous people have complained).I cannot recommend this book at all until the author/publisher corrects this. Very unprofessional behavior.
Amazon Verified review Amazon
Amazon Customer Oct 22, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
R Programming By Example is not worth. Instead to buy this book we have somany alternate books which they explain very clear.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.