Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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
R for Data Science Cookbook (n)
R for Data Science Cookbook (n)

R for Data Science Cookbook (n): Over 100 hands-on recipes to effectively solve real-world data problems using the most popular R packages and techniques

Arrow left icon
Profile Icon Yu-Wei, Chiu (David Chiu)
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
Paperback Jul 2016 452 pages 1st Edition
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
Arrow left icon
Profile Icon Yu-Wei, Chiu (David Chiu)
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
Paperback Jul 2016 452 pages 1st Edition
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
eBook
zł59.99 zł158.99
Paperback
zł197.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 for Data Science Cookbook (n)

Chapter 2. Data Extracting, Transforming, and Loading

This chapter covers the following topics:

  • Downloading open data
  • Reading and writing CSV files
  • Scanning text files
  • Working with Excel files
  • Reading data from databases
  • Scraping web data
  • Accessing Facebook data
  • Working with twitteR

Introduction

Before using data to answer critical business questions, the most important thing is to prepare it. Data is normally archived in files, and using Excel or text editors allows it to be easily obtained. However, data can be located in a range of different sources, such as databases, websites, and various file formats. Being able to import data from these sources is crucial.

There are four main types of data. Data recorded in text format is the simplest. As some users require storing data in a structured format, files with a .tab or .csv extension can be used to arrange data in a fixed number of columns. For many years, Excel has had a leading role in the field of data processing, and this software uses the .xls and .xlsx formats. Knowing how to read and manipulate data from databases is another crucial skill. Moreover, as most data is not stored in a database, one must know how to use the web scraping technique to obtain data from the Internet. As part of this chapter, we introduce...

Downloading open data

Before conducting any data analysis, an essential step is to collect high-quality, meaningful data. One important data source is open data, which is selected, organized, and freely available to the public. Most open data is published online in either text format or as APIs. Here, we introduce how to download the text format of an open data file with the download.file function.

Getting ready

In this recipe, you need to prepare your environment with R installed and a computer that can access the Internet.

How to do it…

Please perform the following steps to download open data from the Internet:

  1. First, visit the http://finance.yahoo.com/q/hp?s=%5EGSPC+Historical+Prices link to view the historical price of the S&P 500 in Yahoo Finance:
    How to do it…

    Figure 1: Historical price of S&P 500

  2. Scroll down to the bottom of the page, right-click and copy the link in Download to Spreadsheet (the link should appear similar to http://real-chart.finance.yahoo.com/table.csv?s=%5EGSPC&d...

Reading and writing CSV files

In the previous recipe, we downloaded the historical S&P 500 market index from Yahoo Finance. We can now read the data into an R session for further examination and manipulation. In this recipe, we demonstrate how to read a file with an R function.

Getting ready

In this recipe, you need to have followed the previous recipe by downloading the S&P 500 market index text file to the current directory.

How to do it…

Please perform the following steps to read text data from the CSV file.

  1. First, determine the current directory with getwd, and use list.files to check where the file is, as follows:
    > getwd()
    > list.files('./')
    
  2. You can then use the read.table function to read data by specifying the comma as the separator:
    > stock_data <- read.table('snp500.csv', sep=',' , header=TRUE)
    
  3. Next, filter data by selecting the first six rows with column Date, Open, High, Low, and Close:
    > subset_data <- stock_data[1:6, c...

Scanning text files

In previous recipes, we introduced how to use read.table and read.csv to load data into an R session. However, read.table and read.csv only work if the number of columns is fixed and the data size is small. To be more flexible in data processing, we will demonstrate how to use the scan function to read data from the file.

Getting ready

In this recipe, you need to have completed the previous recipes and have snp500.csv downloaded in the current directory.

How to do it…

Please perform the following steps to scan data from the CSV file:

  1. First, you can use the scan function to read data from snp500.csv:
    > stock_data3 <- scan('snp500.csv',sep=',', what=list(Date = '', Open = 0, High = 0, Low = 0,Close = 0, Volume = 0, Adj_Close = 0),  skip=1, fill=T)
    Read 16481 records
    
  2. You can then examine loaded data with mode and str:
    > mode(stock_data3)
    [1] "list"
    > str(stock_data3)
    List of 7
     $ Date     : chr [1:16481] "2015-07...

Working with Excel files

Excel is another popular tool used to store and analyze data. Of course, one can convert Excel files to CSV files or other text formats by using Excel. Alternatively, to simplify the process, you can use install and load the xlsx package to read and process Excel data in R.

Getting ready

In this recipe, you need to prepare your environment with R installed and a computer that can access the Internet.

How to do it…

Please perform the following steps to read Excel documents:

  1. First, install and load the xlsx package:
    > install.packages("xlsx")
    > library(xlsx)
    
  2. Access www.data.worldbank.org/topic/economy-and-growth to find world economy indicator data in Excel:
    How to do it…

    Figure 6: World economy indicator

  3. Download world economy indicator data from the following URL using download.file:
    > download.file("http://api.worldbank.org/v2/en/topic/3?downloadformat=excel", "worldbank.xls", mode="wb")
    
  4. Examine the downloaded file with Excel (or...

Reading data from databases

As R reads data into memory, it is perfect for processing and analyzing small datasets. However, as an enterprise accumulates much more data than individuals in their daily lives, database documents are becoming more common for the purpose of storing and analyzing bigger data. To access databases with R, one can use RJDBC, RODBC, or RMySQL as the communications bridge. In this section, we will demonstrate how to use RJDBC to connect data stored in the database.

Getting ready

In this section, we need to prepare a MySQL environment first. If you have a MySQL environment installed on your machine (Windows), you can inspect server status from MySQL Notifier. If the local server is running, the server status should prompt localhost (Online), as shown in the following screenshot:

Getting ready

Figure 8: MySQL Notifier

Once we have our database server online, we need to validate whether we are authorized to access the database with a given username and password by using any database...

Introduction


Before using data to answer critical business questions, the most important thing is to prepare it. Data is normally archived in files, and using Excel or text editors allows it to be easily obtained. However, data can be located in a range of different sources, such as databases, websites, and various file formats. Being able to import data from these sources is crucial.

There are four main types of data. Data recorded in text format is the simplest. As some users require storing data in a structured format, files with a .tab or .csv extension can be used to arrange data in a fixed number of columns. For many years, Excel has had a leading role in the field of data processing, and this software uses the .xls and .xlsx formats. Knowing how to read and manipulate data from databases is another crucial skill. Moreover, as most data is not stored in a database, one must know how to use the web scraping technique to obtain data from the Internet. As part of this chapter, we introduce...

Downloading open data


Before conducting any data analysis, an essential step is to collect high-quality, meaningful data. One important data source is open data, which is selected, organized, and freely available to the public. Most open data is published online in either text format or as APIs. Here, we introduce how to download the text format of an open data file with the download.file function.

Getting ready

In this recipe, you need to prepare your environment with R installed and a computer that can access the Internet.

How to do it…

Please perform the following steps to download open data from the Internet:

  1. First, visit the http://finance.yahoo.com/q/hp?s=%5EGSPC+Historical+Prices link to view the historical price of the S&P 500 in Yahoo Finance:

    Figure 1: Historical price of S&P 500

  2. Scroll down to the bottom of the page, right-click and copy the link in Download to Spreadsheet (the link should appear similar to http://real-chart.finance.yahoo.com/table.csv?s=%5EGSPC&d=6&e...

Reading and writing CSV files


In the previous recipe, we downloaded the historical S&P 500 market index from Yahoo Finance. We can now read the data into an R session for further examination and manipulation. In this recipe, we demonstrate how to read a file with an R function.

Getting ready

In this recipe, you need to have followed the previous recipe by downloading the S&P 500 market index text file to the current directory.

How to do it…

Please perform the following steps to read text data from the CSV file.

  1. First, determine the current directory with getwd, and use list.files to check where the file is, as follows:

    > getwd()
    > list.files('./')
    
  2. You can then use the read.table function to read data by specifying the comma as the separator:

    > stock_data <- read.table('snp500.csv', sep=',' , header=TRUE)
    
  3. Next, filter data by selecting the first six rows with column Date, Open, High, Low, and Close:

    > subset_data <- stock_data[1:6, c("Date", "Open", "High", "Low", "Close...
Left arrow icon Right arrow icon

Key benefits

  • • Gain insight into how data scientists collect, process, analyze, and visualize data using some of the most popular R packages
  • • Understand how to apply useful data analysis techniques in R for real-world applications
  • • An easy-to-follow guide to make the life of data scientist easier with the problems faced while performing data analysis

Description

This cookbook offers a range of data analysis samples in simple and straightforward R code, providing step-by-step resources and time-saving methods to help you solve data problems efficiently. The first section deals with how to create R functions to avoid the unnecessary duplication of code. You will learn how to prepare, process, and perform sophisticated ETL for heterogeneous data sources with R packages. An example of data manipulation is provided, illustrating how to use the “dplyr” and “data.table” packages to efficiently process larger data structures. We also focus on “ggplot2” and show you how to create advanced figures for data exploration. In addition, you will learn how to build an interactive report using the “ggvis” package. Later chapters offer insight into time series analysis on financial data, while there is detailed information on the hot topic of machine learning, including data classification, regression, clustering, association rule mining, and dimension reduction. By the end of this book, you will understand how to resolve issues and will be able to comfortably offer solutions to problems encountered while performing data analysis.

Who is this book for?

This book is for those who are already familiar with the basic operation of R, but want to learn how to efficiently and effectively analyze real-world data problems using practical R packages.

What you will learn

  • • Get to know the functional characteristics of R language
  • • Extract, transform, and load data from heterogeneous sources
  • • Understand how easily R can confront probability and statistics problems
  • • Get simple R instructions to quickly organize and manipulate large datasets
  • • Create professional data visualizations and interactive reports
  • • Predict user purchase behavior by adopting a classification approach
  • • Implement data mining techniques to discover items that are frequently purchased together
  • • Group similar text documents by using various clustering methods

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 29, 2016
Length: 452 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390815
Category :
Languages :
Concepts :
Tools :

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 : Jul 29, 2016
Length: 452 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390815
Category :
Languages :
Concepts :
Tools :

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 zł20 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 zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 666.97
Simulation for Data Science with R
zł221.99
Big Data Analytics with R
zł246.99
R for Data Science Cookbook (n)
zł197.99
Total 666.97 Stars icon

Table of Contents

13 Chapters
1. Functions in R Chevron down icon Chevron up icon
2. Data Extracting, Transforming, and Loading Chevron down icon Chevron up icon
3. Data Preprocessing and Preparation Chevron down icon Chevron up icon
4. Data Manipulation Chevron down icon Chevron up icon
5. Visualizing Data with ggplot2 Chevron down icon Chevron up icon
6. Making Interactive Reports Chevron down icon Chevron up icon
7. Simulation from Probability Distributions Chevron down icon Chevron up icon
8. Statistical Inference in R Chevron down icon Chevron up icon
9. Rule and Pattern Mining with R Chevron down icon Chevron up icon
10. Time Series Mining with R Chevron down icon Chevron up icon
11. Supervised Machine Learning Chevron down icon Chevron up icon
12. Unsupervised Machine Learning 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 Full star icon Half star icon 4.3
(3 Ratings)
5 star 33.3%
4 star 66.7%
3 star 0%
2 star 0%
1 star 0%
Rahul Raoniar Mar 09, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Finally a book for engineering students. After searching 20+ books for Data science with R, finally got it. This book covers almost everything that an engineering student needs during master's or PhD. It covers almost every aspect of data processing like adding, dropping, filtering, merging, shorting and reshaping data set with fantastic libraries like dplyr, data.table and many more. It covers almost every statistical inference and testing techniques such as t-test, ANOVA, Various regression models (Linear, Multiple, Logistic, Step-wise regression etc), Distributions ( Normal, Poison, Binomial etc). This book also covers time series analysis with ARIMA and machine learning for both supervised and unsupervised with k-mean and other clustering techniques. It has one dedicated chapter on plotting functions like ggplot2, ggvis and mapping with spacial data, which provides awesome plots. This book is for all students and data scientist professional those want to explore the statistical characteristics of data sets. This book covers almost every part of data processing using R. The main advantage of this book is that after every code examples it provides detailed description of methodology involved in code. Like for Chi-Square test we can do it in few lines in R, this book provides the step wise code and at the end of the code it describes the theory and equation involved for calculation, which provides a great help for better understanding the underlying concepts.As a PhD scholar in Transportation Engineering, I can say, this is the best book available in market so far for data science with R.
Amazon Verified review Amazon
Sudipta Chakraborty Oct 06, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Today i received it from amazon as expected. Thank you amazon. This book is really good and pretty much helpful for those who are seeking a career in data science or data analytics domain. As of now i am giving 4 star once i done with this book i will be reviewing once again. Thanks
Amazon Verified review Amazon
Prashant Sharma Nov 07, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Its a good book. Must have for all R programmers
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.