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
Free Trial
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (4 Ratings)
Paperback Dec 2017 470 pages 1st Edition
eBook
S$59.99
Paperback
S$74.99
Subscription
Free Trial
Arrow left icon
Profile Icon Omar Trejo Navarro Profile Icon Trejo Navarro
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (4 Ratings)
Paperback Dec 2017 470 pages 1st Edition
eBook
S$59.99
Paperback
S$74.99
Subscription
Free Trial
eBook
S$59.99
Paperback
S$74.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781788292542
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 S$6 each
Feature tick icon Exclusive print discounts
$279.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 S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 208.97
R Data Mining
S$66.99
R Programming By Example
S$74.99
Modern R Programming Cookbook
S$66.99
Total S$ 208.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.