Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning Predictive Analytics with R
Learning Predictive Analytics with R

Learning Predictive Analytics with R: Get to grips with key data visualization and predictive analytic skills using R

eBook
$30.79 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning Predictive Analytics with R

Chapter 2. Visualizing and Manipulating Data Using R

Data visualization is one of the most important processes in data science. Relationships between variables can sometimes more easily be understood visually than relying only on predictive modeling, or statistics, and this most often requires data manipulation. Visualization is the art of examining distributions and relationships between variables using visual representations (graphics), with the aim of discovering patterns in data. As a matter of fact, a number of software companies provide data visualization tools as their sole or primary product (for example, Tableau, Visual.ly). R has built-in capabilities for data visualization. These capabilities can of course (as with almost everything in R) be extended by recourse to external packages. Furthermore, graphics made for a particular dataset can be reused and adapted for another with relatively little effort. Another great advantage of R is of course that it is a fully functional...

The roulette case

Roulette is a betting game which rewards the player's correct prediction of its outcome. The game consists of a ball spinning around a wheel which rotates in the opposite direction. The wheel features 37 numbered pockets. Each of the number has a color (18 are red, 18 are black and one, the zero, is green). The aim of the game is to bet on one or several outcomes regarding the pocket on which the ball lands. Numbers can range from 0 to 36, and several types of bets are available such as the color of the number, it being even or odd, and several other characteristics related to the number or the position on the wheel (as marked on the betting grid). The image below is a representation of an European roulette wheel. The ball is represented by the tiny white circle. In this example it landed on the pocket corresponding to the number 3.

The roulette case

A representation of a roulette wheel

Numbers are ordered on the wheel in such a way that the position of a number on the wheel is as unrelated...

Histograms and bar plots

Roulette is a fascinating example of a betting game using random outcomes. In order to explore some properties of roulette spins, let's visualize some randomly drawn numbers in the range of those in an European roulette game (0 to 36). Histograms allow the graphic representation of the distribution of variables. Let's have a look at it! Type in the following code:

1  set.seed(1)
2  drawn = sample(0:36, 100, replace = T)
3  hist(drawn, main = "Frequency of numbers drawn",
4     xlab = "Numbers drawn", breaks=37)

Here we first set the seed number to 1 (see line 1). For reproducibility reasons, computer generated random numbers are generally not really random (they are in fact called pseudo-random). Exceptions exist, such as numbers generated on the website http://www.random.org (which bases the numbers on atmospheric variations). Setting the seed number to 1 (or any number really) makes sure the numbers we generate here will be the same...

Scatterplots

Until now we have observed frequencies of the relationship between categorical membership (nominal attributes) and frequencies or means. It is also useful to have a look at relationships between numerical attributes. We will rely on scatterplots for this purpose. This will require a little scripting again, as we will examine the relationships between proportions. Let me first introduce the function proportions() which will generate the proportions for us, for all of our nominal attributes. This function takes one argument, DF, and call our attributes() function by default. We could instead give as an argument the data frame with the numbers we have previously drawn and the attributes.

The body of the function computes and returns the transpose of the means of each nominal attributes:

1    proportions = function(n = 100) {
2       DF=attributes(n)
3       return(data.frame(t(colMeans(DF[3:ncol(DF)]))))
4    }

The body of this function calls our attributes() function and passes...

Boxplots

As we can also notice from the scatterplot, whereas most of the samples have a relatively balanced proportion of red or even numbers, these proportions are very small or large in some cases. We could examine the dispersion of those values using a histogram again, but the boxplot is much more interesting, so we will use it instead. Boxplots are representations of the distribution of an attribute. We could have a look at only one attribute by specifying its name as an argument from the boxplot() function. We will instead look at all the arguments at once by giving the data frame as an argument:

boxplot(samples)
Boxplots

Boxplots of all the attributes

As can be seen from the boxplots, the proportions of red, black, odd, even, numbers below 18, and numbers higher than 18 are a little below 50% on average, which is what is expected as 18 of 37 numbers are in each of these categories. We can also notice that the average proportion of numbers between 1 and 12, 13 and 24, 25 and 36, as well as numbers...

Line plots

Line plots provide the same information as bar plots. They might allow to understand relationships between attributes better because the values are linked by lines which give a better feeling of the difference between the values. We will investigate the variability of the proportions of each attribute by plotting its proportion from each sample. On line 1, we will first configure the plotting area contain 12 plots (as we have 12 attributes). Notice we use the oma attribute to set the outer margin, and the mar attribute to set the inner margin. On line 2, we set the names to be used in the titling of the axis (using the ylab attribute, see line 4). We then iteratively create, for each attribute, a graph plotting each value (lines 3 to 5). The type attribute is set to l (line 5) in order to plot lines instead of dots as in a scatterplot.

1    par(mfrow=c(4,3), oma = rep(0.1,4), mar = rep(4,4))
2    names=colnames(samples)
3    for (i in 1:ncol(samples)){ 
4       plot(samples[,i...

Application – Outlier detection

You might remember that at the beginning of the chapter, we noticed in the stacked bar plot that in our sample of 1,000 roulette spins, the zero was drawn about twice as often as we would expect. We just mentioned it but didn't really have a point of comparison. We now have proportions from 100 samples and thus can examine this a little further. The proportion of zeros can be obtained from the data we have as we simply have to subtract from 1, the sum of proportions of red and black numbers for each of the samples. So let's do this, and add the attribute to the data frame, and get the mean value of this proportion:

samples$isZero = 1-(samples$isRed+samples$isBlack)
Mean = mean(samples$isZero)
Mean

The mean value is 0.0277. We can compute the value we would expect is 1/37, which is 0.0270. The average value of the proportion of zeros in all our 100 samples is therefore almost identical to the expected value. This in no way means that there are...

Formatting plots

Plots in R can be formatted in many ways. We have already seen some of them in this chapter. In this section, we briefly explore some of these options. Let's go back to the data frame containing the 1,000 roulette spins and examine the relationship between the position on the roulette and the number by color. On line 1, we call the plot function. On line 2, we specify the attributes to be plotted, and add a little jitter to the data, using the jitter() function, otherwise, many points will be stacked over each other. The factor argument of this function controls the amount of jittering. We also reduce the size of the dots, using the cex attribute (line 3). We then title our graph and axes (lines 4 to 6).

Finally, we want to color the dots according to whether the number drawn is red or not (line 7). For this purpose, we use the col attribute:

1    plot( 
2      jitter(Data$position, factor=4),jitter(Data$number, factor=4),
3      cex = 0.5,
4      main = "Relationship...

Summary

In this chapter, we have examined a number of possible ways to explore data visually. We have used the flexibility of R to produce samples programmatically to generate data on the fly, which we have used to illustrate how to use basic plots. We have examined some of the associations in the game of roulette and developed functions according to our analytical needs. We have also examined how to recode data, and use only a subset of data, and introduced the concept of multiple sampling.

The next chapter will deal with more advanced graphs using the lattice package. This comes in handy when dealing with several group memberships (for example, ethnicity and gender at once).

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Acquire predictive analytic skills using various tools of R
  • Make predictions about future events by discovering valuable information from data using R
  • Comprehensible guidelines that focus on predictive model design with real-world data

Description

This book is packed with easy-to-follow guidelines that explain the workings of the many key data mining tools of R, which are used to discover knowledge from your data. You will learn how to perform key predictive analytics tasks using R, such as train and test predictive models for classification and regression tasks, score new data sets and so on. All chapters will guide you in acquiring the skills in a practical way. Most chapters also include a theoretical introduction that will sharpen your understanding of the subject matter and invite you to go further. The book familiarizes you with the most common data mining tools of R, such as k-means, hierarchical regression, linear regression, association rules, principal component analysis, multilevel modeling, k-NN, Naïve Bayes, decision trees, and text mining. It also provides a description of visualization techniques using the basic visualization tools of R as well as lattice for visualizing patterns in data organized in groups. This book is invaluable for anyone fascinated by the data mining opportunities offered by GNU R and its packages.

Who is this book for?

If you are a statistician, chief information officer, data scientist, ML engineer, ML practitioner, quantitative analyst, and student of machine learning, this is the book for you. You should have basic knowledge of the use of R. Readers without previous experience of programming in R will also be able to use the tools in the book.

What you will learn

  • Customize R by installing and loading new packages
  • Explore the structure of data using clustering algorithms
  • Turn unstructured text into ordered data, and acquire knowledge from the data
  • Classify your observations using Naïve Bayes, k-NN, and decision trees
  • Reduce the dimensionality of your data using principal component analysis
  • Discover association rules using Apriori
  • Understand how statistical distributions can help retrieve information from data using correlations, linear regression, and multilevel regression
  • Use PMML to deploy the models generated in R
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 24, 2015
Length: 332 pages
Edition : 1st
Language : English
ISBN-13 : 9781782169352
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Sep 24, 2015
Length: 332 pages
Edition : 1st
Language : English
ISBN-13 : 9781782169352
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 148.97
Learning Predictive Analytics with R
$54.99
Learning Bayesian Models with R
$38.99
Machine Learning with R
$54.99
Total $ 148.97 Stars icon

Table of Contents

17 Chapters
1. Setting GNU R for Predictive Analytics Chevron down icon Chevron up icon
2. Visualizing and Manipulating Data Using R Chevron down icon Chevron up icon
3. Data Visualization with Lattice Chevron down icon Chevron up icon
4. Cluster Analysis Chevron down icon Chevron up icon
5. Agglomerative Clustering Using hclust() Chevron down icon Chevron up icon
6. Dimensionality Reduction with Principal Component Analysis Chevron down icon Chevron up icon
7. Exploring Association Rules with Apriori Chevron down icon Chevron up icon
8. Probability Distributions, Covariance, and Correlation Chevron down icon Chevron up icon
9. Linear Regression Chevron down icon Chevron up icon
10. Classification with k-Nearest Neighbors and Naïve Bayes Chevron down icon Chevron up icon
11. Classification Trees Chevron down icon Chevron up icon
12. Multilevel Analyses Chevron down icon Chevron up icon
13. Text Analytics with R Chevron down icon Chevron up icon
14. Cross-validation and Bootstrapping Using Caret and Exporting Predictive Models Using PMML Chevron down icon Chevron up icon
A. Exercises and Solutions Chevron down icon Chevron up icon
B. Further Reading and References Chevron down icon Chevron up icon
Index 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
(2 Ratings)
5 star 0%
4 star 50%
3 star 0%
2 star 50%
1 star 0%
r pike Jul 18, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I enjoyed reading this. As a beginner in predictive analytics, for me, it was informative. The subject matter is vast and no one book would be able to get someone started in the field of study but this was a good start for me.
Amazon Verified review Amazon
Dimitri Shvorob Mar 03, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Packt's conveyor is not slowing down: only three months ago I surveyed their fresh crop of "data science with R" offerings"Mastering Predictive Analytics with R" by Forte, £32.99"Mastering Machine Learning with R" by Lesmeister, £34.99"R Data Analysis Cookbook" by Viswanathan and Viswanathan, £29.99"Machine Learning with R Cookbook" by Yu-Wei, £30.99and now there are four more:"Unsupervised Learning with R" by Pacheco, £25.99"Data Analysis with R" by Fischetti, £34.99"Learning Predictive Analytics with R" by Mayor, £31.99"Mastering Data Analysis with R" by Daroczi, £34.99I have not yet seen Daroszi's book, but Fischetti's book gets my "thumbs up", Pacheco's is an easy "thumbs down", and Mayor's is ... right there with Pacheco's. The book really feels behind the times - cf. use of "lattice" over "ggplot2", and of R Commander instead of RStudio - and the writing is seriously subpar. Contentwise, it's all familiar stuff - even the dreadful book by Lesmeister could manage "caret" usage examples - and coverage is actually on the narrow side. What could *possibly* be the book's "unique selling proposition"?Kabacoff, Forte, Lantz, Cotton, Kuhn - check out the books by any of these authors, and erase this one from your memory.UPD. With the benefit of a little more life experience, I would say: don't spend your time on *any* R book. Python is the way to go.
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 the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon