This introductory chapter will get you started with the basics of R which include various constructs, useful data structures, loops and vectorization. If you are already an R wizard, you can skim through these sections and dive right into the next part which talks about what machine learning actually represents as a domain and the main areas it encompasses. We will also talk about different machine learning techniques and algorithms used in each area. Finally, we will conclude by looking at some of the most popular machine learning packages in R, some of which we will be using in the subsequent chapters.
If you are a data or machine learning enthusiast, surely you would have heard by now that being a data scientist is referred to as the sexiest job of the 21st century by Harvard Business Review.
There is a huge demand in the current market for data scientists, primarily because their main job is to gather crucial insights and information from both unstructured and structured data to help their business and organization grow strategically.
Some of you might be wondering how machine learning or R relate to all this! Well, to be a successful data scientist, one of the major tools you need in your toolbox is a powerful language capable of performing complex statistical calculations and working with various types of data and building models which help you get previously unknown insights and R is the perfect language for that! Machine learning forms the foundation of the skills you need to build to become a data analyst or data scientist, this includes using various techniques to build models to get insights from data.
This book will provide you with some of the essential tools you need to be well versed with both R and machine learning by not only looking at concepts but also applying those concepts in real-world examples. Enough talk; now let's get started on our journey into the world of machine learning with R!
In this chapter, we will cover the following aspects:
Delving into the basics of R
Understanding the data structures in R
Working with functions
Controlling code flow
Taking further steps with R
Understanding machine learning basics
Familiarizing yourself with popular machine learning packages in R
It is assumed here that you are at least familiar with the basics of R or have worked with R before. Hence, we won't be talking much about downloading and installations. There are plenty of resources on the web which provide a lot of information on this. I recommend that you use RStudio which is an Integrated Development Environment (IDE), which is much better than the base R Graphical User Interface (GUI). You can visit https://www.rstudio.com/ to get more information about it.
Note
For details about the R project, you can visit https://www.r-project.org/ to get an overview of the language. Besides this, R has a vast arsenal of wonderful packages at its disposal and you can view everything related to R and its packages at https://cran.r-project.org/ which contains all the archives.
You must already be familiar with the R interactive interpreter, often called a Read-Evaluate-Print
Loop (REPL). This interpreter acts like any command line interface which asks for input and starts with a >
character, which indicates that R is waiting for your input. If your input spans multiple lines, like when you are writing a function, you will see a +
prompt in each subsequent line, which means that you didn't finish typing the complete expression and R is asking you to provide the rest of the expression.
It is also possible for R to read and execute complete files containing commands and functions which are saved in files with an .R
extension. Usually, any big application consists of several .R
files. Each file has its own role in the application and is often called as a module. We will be exploring some of the main features and capabilities of R in the following sections.
The most basic constructs in R include variables and arithmetic operators which can be used to perform simple mathematical operations like a calculator or even complex statistical calculations.
Remember that everything in R is a vector. Even the output results indicated in the previous code snippet. They have a leading [1] symbol indicating it is a vector of size 1
.
You can also assign values to variables and operate on them just like any other programming language.
The most basic data structure in R is a vector. Basically, anything in R is a vector, even if it is a single number just like we saw in the earlier example! A vector is basically a sequence or a set of values. We can create vectors using the :
operator or the c
function which concatenates the values to create a vector.
You can clearly in the previous code snippet, that we just added two vectors together without using any loop, using just the +
operator. This is known as vectorization and we will be discussing more about this later on. Some more operations on vectors are shown next:
Output:
You might be confused with the second operation where we tried to multiply a smaller vector with a bigger vector but we still got a result! If you look closely, R threw a warning also. What happened in this case is, since the two vectors were not equal in size, the smaller vector in this case c(2, 4)
got recycled or repeated to become c(2, 4, 2, 4, 2)
and then it got multiplied with the first vector c(1, 3, 5, 7 ,9)
to give the final result vector, c(2, 12, 10, 28, 18)
. The other functions mentioned here are standard functions available in base R along with several other functions.
Tip
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top
Click on Code Downloads & Errata
Enter the name of the book in the Search box
Select the book for which you're looking to download the code files
Choose from the drop-down menu where you purchased this book from
Click on Code Download
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
Since you will be dealing with a lot of messy and dirty data in data analysis and machine learning, it is important to remember some of the special values in R so that you don't get too surprised later on if one of them pops up.
The main values which should concern you here are Inf
which stands for Infinity, NaN
which is Not a Number, and NA
which indicates a value that is missing or Not Available. The following code snippet shows some logical tests on these special values and their results. Do remember that TRUE
and FALSE
are logical data type values, similar to other programming languages.
The functions are pretty self-explanatory from their names. They clearly indicate which values are finite, which are finite and checks for NaN
and NA
values respectively. Some of these functions are very useful when cleaning dirty data.
Here we will be looking at the most useful data structures which exist in R and use using them on some fictional examples to get a better grasp on their syntax and constructs. The main data structures which we will be covering here include:
Vectors
Arrays and matrices
Lists
Data frames
These data structures are used widely inside R as well as by various R packages and functions, including machine learning functions and algorithms which we will be using in the subsequent chapters. So it is essential to know how to use these data structures to work with data efficiently.
Just like we mentioned briefly in the previous sections, vectors are the most basic data type inside R. We use vectors to represent anything, be it input or output. We previously saw how we create vectors and apply mathematical operations on them. We will see some more examples here.
Here we will look at ways to initialize vectors, some of which we had also worked on previously, using operators such as :
and functions such as c
. In the following code snippet, we will use the seq
family of functions to initialize vectors in different ways.
One of the most important operations we can do on vectors involves subsetting and indexing vectors to access specific elements which are often useful when we want to run some code only on specific data points. The following examples show some ways in which we can index and subset vectors:
Now we look at how we can name vectors. This is basically a nifty feature in R where you can label each element in a vector to make it more readable or easy to interpret. There are two ways this can be done, which are shown in the following examples:
Output:
Output:
Output:
Thus, you can see, it becomes really useful to annotate and name vectors sometimes, and we can also subset and slice vectors using element names rather than values.
Vectors are one dimensional data structures, which means that they just have one dimension and we can get the number of elements they have using the length
property. Do remember that arrays may also have a similar meaning in other programming languages, but in R they have a slightly different meaning. Basically, arrays in R are data structures which hold the data having multiple dimensions. Matrices are just a special case of generic arrays having two dimensions, namely represented by properties rows
and columns
. Let us look at some examples in the following code snippets in the accompanying subsection.
First we will create an array that has three dimensions. Now it is easy to represent two dimensions in your screen, but to go one dimension higher, there are special ways in which R transforms the data. The following example shows how R fills the data (column first) in each dimension and shows the final output for a 4x3x3 array:
Output:
Like I mentioned earlier, a matrix is just a special case of an array. We can create a matrix using the matrix
function, shown in detail in the following example. Do note that we use the parameter byrow
to fill the data row-wise in the matrix instead of R's default column-wise fill in any array or matrix. The ncol
and nrow
parameters stand for number of columns and rows respectively.
Output:
Just like we named vectors and accessed element names, will perform similar operations in the following code snippets. You have already seen the use of the dimnames
parameter in the preceding examples. Let us look at some more examples as follows:
Output:
Output:
Output:
To access details of dimensions related to arrays and matrices, there are special functions. The following examples show the same:
A lot of machine learning and optimization algorithms deal with matrices as their input data. In the following section, we will look at some examples of the most common operations on matrices.
We start by initializing two matrices and then look at ways of combining the two matrices using functions such as c
which returns a vector, rbind
which combines the matrices by rows,
and cbind
which does the same by columns.
Output:
Output:
Output:
Output:
Output:
Now we look at some of the important arithmetic operations which can be performed on matrices. Most of them are quite self-explanatory from the following syntax:
Output:
Output:
Output:
Output:
Output:
Output:
Output:
The preceding arithmetic operations are just some of the most popular ones amongst the vast number of functions and operators which can be applied to matrices. This becomes useful, especially in areas such as linear optimization.
Lists are a special case of vectors where each element in the vector can be of a different type of data structure or even simple data types. It is similar to the lists in the Python programming language in some aspects, if you have used it before, where the lists indicate elements which can be of different types and each have a specific index in the list. In R, each element of a list can be as simple as a single element or as complex as a whole matrix, a function, or even a vector of strings.
We will get started with looking at some common methods to create and initialize lists in the following examples. Besides that, we will also look at how we can access some of these list elements for further computations. Do remember that each element in a list can be a simple primitive data type or even complex data structures or functions.
Output:
Output:
You can see from the preceding examples how easy it is to access any element of the list and use it for further computations, such as the cos
function.
Data frames are special data structures which are typically used for storing data tables or data in the form of spreadsheets, where each column indicates a specific attribute or field and the rows consist of specific values for those columns. This data structure is extremely useful in working with datasets which usually have a lot of fields and attributes.
We can create data frames easily using the data.frame
function. We will look at some following examples to illustrate the same with some popular superheroes:
Output:
Output:
Output:
The str
function talks in detail about the structure of the data frame where we see details about the data present in each column of the data frame. There are a lot of datasets readily available in R base which you can directly load and start using. One of them is shown next. The mtcars
dataset has information about various automobiles, which was extracted from the Motor Trend U.S. Magazine of 1974.
Output:
There are a lot of operations we can do on data frames, such as merging, combining, slicing, and transposing data frames. We will look at some of the important data frame operations in the following examples.
It is really easy to index and subset specific data inside data frames using simplex indexes and functions such as subset
.
Output:
Output:
Output:
Output:
We will now look at some more complex operations, such as combining and merging data frames.
Output:
Output:
Output:
Output:
From the preceding operations it is evident that rbind
and cbind
work in the same way as we saw previously with arrays and matrices. However, merge lets you merge the data frames in the same way as you join various tables in relational databases.