Getting Started With R Programming
Getting Started With R Programming
with
R Programming
Learn the fundamentals of R programming language and how to start using it for finance.
In this ebook, you will learn the fundamentals of R programming language and how to start
using it for finance.
R is one of the leading programming languages used in the financial industry where
professionals have applied and used R in various areas such as analyzing financial data,
building and evaluate statistical models, constructing optimized portfolios, credit risk modelling
and more. R has become a tool of choice for financial professionals in their everyday data
analysis needs. As the importance of analytics and data science continues to grow in the
financial sector, every finance professional will boost their career by having R programming
skills in their arsenal.
In this ebook, we will start with the basics of R programming starting with how to setup the tools
to work with r programming. Then we will learn the basic concepts in R programming, starting
from variables and basic operations, and then moving on to handling data structures such as
vectors, matrices, data frames and lists.
Installing R
You can install R on any computer whether it is running Windows, Mac or Linux.
Download the R software by visiting the Comprehensive R Archive Network (CRAN) at this
URL:
[Link]
Make sure that you download the file relevant for your operating system:
2 [Link]
R Download Page
Installation of R is quite simple. Below instructions will guide you on how to install R on
Windows and Mac operating system.
Install R on Windows
1. Double-click on the icon for the downloaded file ([Link]) to run it.
2. When the window opens, select a language (e.g., English) and click ‘OK’.
3 [Link]
3. The R Setup Wizard will appear in a window. Click “Next” at the bottom of the R Setup
wizard window.
4. Click Next to continue.
5. On the next screen you will be asked to select a destination location. By default, a
location such as ‘C:\Program Files\R\R-3.3.2’, will already be filled. Leave the location as
is and click next to continue.
6. On the next screen you will be asked to select Components. Keep all components
selected, and click Next.
7. The next page says “Startup options” at the top. Keep the default option of ‘No’. Click
“Next” again.
8. The next page says “Select start menu folder” at the top. Click “Next” again.
9. The next page says “Select additional tasks” at the top. Click “Next” again.
10. R will now start installing. This will take about a minute. When R has finished, you will
see “Completing the R for Windows Setup Wizard” appear. Click “Finish”.
Install R on Mac
1. Double-click on the icon for the downloaded file ([Link]) to run it.
2. When the window opens, select a language (e.g., English) and click ‘OK’.
Start R
You can now start R by double clicking on the R icon your desktop. The R console (a rectangle)
should pop up:
4 [Link]
Note that R works exactly the same on both Mac and Windows. There are some minor UI
differences, however, the functionality is exactly the same.
Now that you have R running on your system and you can see the R console, let’s start by
having r do some basic arithmetic for us. We can perform all arithmetic operations in R as you
would do on a regular calculator.
Let’s begin by clearing the console screen. To do so press CTRL+L. This will clear everything
from console.
• Addition: +
• Subtraction: -
• Multiplication: *
5 [Link]
• Division: /
• Exponentiation: ^
• Modulo: %%
To calculate the sum of 3 and 5, simply type 3 + 5 in the console and hit Enter. R will compile
what you typed, calculate the result and print that result as a numerical value.
Similarly, you can type a string (which is entered in quotes) and hit enter and R will output the
result as a string. R understands your input and distinguishes between character string and
numerical value.
The other arithmetic operators work in the same way. Try the following in your R console.
The last one, the modulo operation, finds the remainder after division of one number by
another. The above expression 26 modulo 3 would evaluate to 2 because 26 divided by 3
leaves a quotient of 8 and a remainder of 2.
Adding Comments
While writing programs, it is important to add comments in various places so that when you are
reviewing a program in future, the comments can help you understand your program. To add a
comment, add the symbol # before the text that you want to show as comment. For example:
# This is a comment
6 [Link]
Setting Up a Working Directory in R
When beginning to work with R code, the first thing that you need to do is setup a working
directory. A working directory is a location on on your computer from which R will read and write
files to. You can choose any location/folder on your computer where you want to save your
code and set that as the working directory.
The following example shows how to set the working directory in R to the folder "C:\r-
programming\data" on the C drive in Windows.
setwd("C:/r-programming/data")
Note: You need to first create a directory called r-programming and then another directory
within it called 'data'. Check that you are able to access this directory "C:/r-programming/data"
from Windows Explorer. Once the directory exists, you will be able to use the setwd() command
to set that as the working directory.
setwd("/Users/User Name/Documents/FOLDER")
Note that you must use the forward slash / or double backslash \\ in R! The Windows format of
single backslash will not work.
You can check that your working directory has been correctly set by using the
function getwd() as shown below:
getwd()
[1] "C:/r-programming/data"
7 [Link]
Once you've set a working directory, you can then further navigate to a subfolder by using the
same command. In this example, I have a sub-folder called 'arithmetic' for some r code.
getwd()
[1] "C:/r-programming/data"
setwd("arithmetic")
getwd()
[1] "C:/r-programming/data/arithmetic"
If you want to move back to the parent directory, you can do it as follows:
setwd("../")
getwd()
[1] "C:/r-programming/data"
Once we are in a particular folder you read and write files in that folder from R. We can type the
command dir() to get a list of files in that folder.
getwd()
[1] "C:/r-programming/data"
setwd("arithmetic")
getwd()
[1] "C:/r-programming/data/arithmetic"
dir()
[1] "arithmetic-examples.r"
As you can see we have a file called arithmetic-examples.r in the 'data/arithmetic' folder.
8 [Link]
Installing and Using RStudio with R
While R comes with a neat console that you can use for all your R programming needs, you can
complement it with RStudio which is a GUI built on top of R and makes it very easy to manage
your programming requirements.
Installing RStudio
You can download RStudio from the following link:
[Link]
On the page you will come across multiple choices for downloading the software.
• From a licensing perspective, there is a personal license (which is free) and then there is
a commercial license. For our purpose, you need the personal license.
• Also, there are two versions for the software: 1) RStudio Desktop and 2) RStudio Server.
For now, you just need to download RStudio Desktop.
So, among all the choices available, you will need to download RStudio Desktop with Personal
License.
9 [Link]
When you click the download button, it will present you with a choice of download files. You
must download the file suitable for your operating system.
Once the installer is downloaded, click on it and install it. Follow the onscreen instructions to
complete the installation. Once installed, open the application and now you’re running RStudio.
You can quickly try some arithmetic to get the idea of how to use the interface.
For example:
10 [Link]
RStudio Orientation
RStudio being a GUI makes working with R very user-friendly and allows you to execute basic
commands without writing commands manually. This includes things like opening a script,
import/export .csv files, manage R packages, get help, etc. In general, it accelerates and
simplifies these general tasks.
1. The upper left window is the script section where you write all your code.
2. The upper right window is the environment. This is the place where all the objects you
create in your current R session al listed. For example, all datasets you have loaded will
appear here, along with any other objects you have created (special text formats,
vectors, etc). If you click on the History tab, you will see the complete history of code you
have typed, over all sessions
3. The lower left window is the R console. This is the same as the R console we have
already seen. This is the place where the actual calculations take place. The script
section sends the code to the console when you click the ‘Run’ button in the script
section. Just like you did in R Console, you can also write the code directly in R Console,
but that’s not effective as you cannot manipulate it.
11 [Link]
4. The lower right window contains five tabs.
Files
This tab shows you all the files you have saved in your RStudio account. The buttons across
the top of the tab allow you to upload additional files, delete files, rename files, and many more
functions.
Plots
When you run code in the Console that creates a plot, the Plots tab will be automatically
selected. Any time you want to view plots, you can select this tab manually, but it will be
selected when you run plot code. Notice the arrow buttons at the top left of the pane; these
allow you to scroll through all the plots you have created in a session.
Packages
This tab allows you to see the list of all the packages (add-ons to the R code) you have access
to, and which are loaded in already.
Help
This tab will be automatically selected whenever you run help code in the Console, but you can
access it at any time by clicking on the tab.
help(plot)
Viewer
RStudio includes a Viewer pane that can be used to view local web content. We will not be
using this till much later in the book.
As we go along in the book, you will get more familiar with RStudio and various features it
offers. When you first start RStudio, you may not see the script window. You can create a new
script window, by just clicking the ‘New Script’ button, as shown below:
12 [Link]
Using Variables in R
In R programming, we will be using variables all the time, so it is important to understand what a
variable is and how it works in R.
A variable refers to a named storage that allows us to store data which our R programs can
refer to and manipulate. A variable in R can store a value or an object (more on objects later).
For example, we can store value ’50’ in a variable called ‘x’. This is called variable assignment,
that is, the variable ‘x’ is assigned value ’50’.
The variables can be assigned values using leftward, rightward and equal to operator, however,
the most common way is to use the leftward operator ( <- )
Once we have assigned a value to a variable, we can print it by just calling the variable name or
by using the print() or the cat() function.
x = 50
y <- "table"
100 -> z
print (x)
13 [Link]
cat ("z is ", z ,"\n")
[1] 50
x is 50
y is table
z is 100
In RStudio, there are various ways you can execute the R script.
• Select a code line and Click the ‘Run’ button in the script window. This will execute that
line in the code. Select multiple lines of code and click the ‘Run’ button in the script
window. This will execute all the selected lines in the code.
• To execute the entire script (using the Source command), press CTRL+SHIFT+ENTER.
This will execute the entire script with each source command printed in the console. This
is called Source with Echo.
• You can also press CTRL+SHIFT+S to run the Source command, but without Echo. This
means that only the output will be printed to console, not the source commands.
In R, you will create variables for these stocks and assign values to them. After that you can
calculate the total stocks in portfolio by performing arithmetic operations on these variables and
assign the total value to a new variable.
GOOG <- 5
MSFT <- 7
# Add the two variables to get the total stocks in the portfolio
14 [Link]
GOOG + MSFT
print (TOTALSTOCKS)
Try running this script in RStudio. Also try to run it using different commands described above
and notice the difference in the output:
• Select all lines of code and press CTRL + ENTER (Or press the R button) to execute all
lines of the code.
• Press CTRL + SHIFT + ENTER to execute the script using the Source command with
each source command printed in the console (Source with Echo).
• Press CTRL + SHIFT + S to execute the script using the Source command with each
source command without echoing the commands in the console.
Change in Environment
As you assign the variables, you will also notice one more important change. As we learned
earlier, all the objects you create in your current R session will be added to the environment. In
this case, you will see three variables in the environment as shown below:
15 [Link]
Variable Types
r is smart enough to understand the type of data you’re assigning to the variables. In the above
examples, the values assigned were numeric and R could interpret them as numeric therefore
allowed us to add the values in the two variables. But what will happen if one variable has a
numeric value and the other has a character value and you try adding the two? In such a
situation, r will throw an error and will ask you to provide numeric data type for the binary
operation.
GOOG <- 5
# Add the two variables to get the total stocks in the portfolio
GOOG + MSFT
16 [Link]
Data Types in R
In R programming, there are five basic data types. Also, everything in R is an object, so we will
refer to these data types as classes of objects. So, these five types of objects are:
• Numeric
• Integer
• Complex
• Logical
• Character
Numeric
In R, decimal values such as 8.5 are numeric. You can assign a numeric value to a variable and
then that variable will be of numeric data type.
For any variable or object, you can check it's data type by using the class command.
x <- 8.5
[1] 8.5
class(x)
[1] "numeric"
17 [Link]
Integer
Integers are the natural numbers such as 1, 2, 3, etc. In R, when you assign a number to a
variable, it is by default of the numeric class type. In order to create an integer variable, we use
a function called [Link](). This ensures that the variable created is indeed an integer.
x <- 8
class(x)
[1] "numeric"
y <- [Link](8)
class(y)
[1] "integer"
# It is an integer now
18 [Link]
Complex
In R, a complex value is defined using a pure imaginary value <em>i</em>.
x = 1 + 2i
[1] 1+2i
class(x)
[1] "complex"
Logical
Logical values are boolen values (TRUE or FALSE) often created by comparison between
variables.
x <- 5
y <- 7
z <- y < x
[1] FALSE
class(z)
19 [Link]
[1] "logical"
Character
Character values are string or text values. We can create a character type variable by assigning
a string to the variable. Notice the use of double quotes.
x <-"John Doe"
If we have an object of some other data type (e.g., numeric), we can convert it into character
type using the [Link]() function.
x <- 8.75
[1] 8.75
class(x)
[1] "numeric"
y <- [Link](x)
20 [Link]
[1] "8.75"
class(y)
[1] "character"
x = TRUE; y = FALSE
[1] FALSE
[1] TRUE
[1] FALSE
21 [Link]
lname <- 'Doe'
paste(fname, lname)
[1] "GOOG"
The sprintf() function allows you to create strings as output using formatted data. For example:
See the special syntax %s. Each % is referred to as a slot, which is basically a placeholder for a
variable that will be formatted. The values after the comma are the variables or values that will
be filled in each slot.
Getting Help
We can find many more functions for these data types in the R documentation. For each
function, the help also provides details about how to use these functions. For example, you can
22 [Link]
get help for sprintf() function by using the command help('sprintf'). The documentation will
open in the help window (bottom right).
In R, a vector is a series of data elements of the same data type, for example, a series of
numbers, a series of characters, or a series of logical values. In finance, for example, the daily
profit/loss from your stock investments could be represented as a vector. A vector is also
referred to as a one-dimensional array.
An important point to remember is that within a vector, all the data elements must be of the
same type, i.e., you cannot mix different data types in the same vector.
In R, you can create a vector using the combine() function. For example, here is a vector
containing three numeric values 5, 7 and 8.
c(5,7,8)
[1] 5 7 8
Let's say John and Ivan, two colleagues engage in day trading for a week and want to analyze
their daily performance. Their daily profit and loss from the trading activity is shown below:
We can use this data in R by creating vectors and assigning them to variables.
23 [Link]
ivan_earnings <- c(-30,-60,80,-250,200)
john_earnings
ivan_earnings
Run this script in RStudio (CTRL+ENTER) and you will see the results in RConsole.
john_earnings
ivan_earnings
Now that we have the data, we can start working with it to measure performance.
Vector Operations
We will use this earnings data to understand how to perform some important arithmetic
operations on vectors.
24 [Link]
Combined Earnings Per Day
We can calculate the combined earnings of both John and Ivan by just adding the two vectors.
When you add two vectors, the addition is performed member-wise (i.e., each element in the
vector is added to the element on the same index in the other vector.
total_earnings_per_day
Run this script in your computer and compare the results with the ones below:
total_earnings_per_day
As you can see, earnings for each day are added and assigned to the new variable.
Total Earnings
The next thing we want to know is - "What were their total earnings for the whole week?"
We can calculate thus using the Sum() function in R which calculates the sum of all elements of
a vector.
25 [Link]
john_earnings <- c(120,-40,25,-130,260)
john_total
ivan_total
total_earnings
Run this script in your computer and compare the results with the ones below:
john_total
[1] 235
ivan_total
[1] -60
total_earnings
[1] 175
26 [Link]
Compare Performance
By visually analyzing the above numbers we already know that John has performed much
better than Ivan. However, when we deal with large datasets, such visual scans will not be
possible. So, we can give the job of comparing performance to R script.
In the following script, we compare performance as a daily level as well as total. To compare
the daily performance, we just have to compare the two vectors. For example, we can check
"Did John perform better than Ivan each day?". To do so, we can use the logical operator to
compare the two vectors. R will automatically compare each element in the vector and return a
boolen value.
john_vs_ivan
overall_perfromance
27 [Link]
The results should match our visual understanding of the numbers:
john_vs_ivan
overall_perfromance
[1] TRUE
Difference
difference
28 [Link]
[1] 150 20 -55 120 60
Vector Index
We can retrieve individual values from a vector by referring to its index. For example, you can
select the first element in the vector by typing vector_name[1]. Similarly, you can select
multiple values from the vector by using the notations demonstrated below:
john_earnings[3]
[1] 25
john_earnings[c(2,5)]
john_earnings[2:4]
29 [Link]
# John's earnings in the week
#If you're applying these names to multiple vectors, you can even
#create a new vector with these names and then assign it.
john_earnings
ivan_earnings
john_earnings
30 [Link]
Select Only Positive Earnings
Let's learn a few more things about vectors using our earnings example. Let's say we want to
create a new variable, which contains only the positive earnings. In this case we will use the
combined earnings vector for John and Ivan.
Step 1: Create a logical vector that tells us on which days we have positive
earnings
#Total Earnings
positive_vector
31 [Link]
Step 2 is to use the positive selection vector to slice the positive earnings
from total_earnings vector.
positive_earning_days
90 105 460
In the second step, we used the logical index vector to slice our earnings factor. If the logical
value is TRUE, the member is included in the resulting slice, otherwise not.
Matrices in R Programming
A matrix is a table of numbers. In math text, it is conventional to denote matrices with bold
letters. For example, consider a matrix D of the prices of the securities on first three days of the
week.
D =
64 31
65 28
66 35
This matrix is {3*2} matrix (pronounced "3 by 2") . The number of rows is given first, followed by
the number of columns. The Matrix D shows that on the first day, the bond was worth $64 and
the stock was worth $31. On the second day the bond was worth $65 and the stock $28. On the
third day the bond was worth $66 and the stock $35.
With this data in place, we can answer many analytics questions considering someone was
holding these assets in their portfolio. Let's learn how to use matrices in R and then how to
perform statistical analysis on them.
32 [Link]
Defining a Matrix in R
Let's say we have the above data in the form of a vector:
We know that this data represents three rows with each row containing the bond price and the
stock price. In R, we can use this vector to create a matrix using the matrix() function as shown
below:
# Price data each number pair represents the bond an dstock price
price_matrix
• The first argument is the data that the matrix function will convert into rows and columns.
• The second argument nrow indicates that the matrix will have three rows. A similar
argument ncol could be used to indicate the number of columns.
price_matrix
[,1] [,2]
33 [Link]
[1,] 64 31
[2,] 65 28
[3,] 66 35
In R, we can assign names to the matrix using the rownames() and colnames() functions as
shown below:
price_matrix
price_matrix
Bond Stock
Mon 64 31
Tue 65 28
Wed 66 35
Another easy way to assign names to a matrix is to use the dimnames() function, as shown
below. Note the use of list() function which we will discuss in the upcoming lessons. This list
has two objects, the first is the vector for row names and the second is the vector for column
names.
34 [Link]
# Use the dimnames function to assign names to matrix elements
price_matrix
Below R script shows some different ways of selecting the matrix elements:
price_matrix
Bond Stock
Mon 64 31
Tue 65 28
Wed 66 35
# What is the bond price on 3rd day? (3rd row and 1st column)
price_matrix[3,1]
[1] 66
price_matrix[,2]
price_matrix[2,]
35 [Link]
Bond Stock
65 28
price_matrix[c(1,3),]
Bond Stock
Mon 64 31
Wed 66 35
price_matrix[2:3,2]
Tue Wed
28 35
1. Let's say that you hold 5 quantity each of this bond and stock. We can multiple
the price_matrix to get the dollar holding value of your assets. We store this in the
matrix portfolio_value.
2. Now that we have the portfolio values, we can calculate the total portfolio value on each
day by adding the value of stocks and bonds. This can be done using
the rowSums() function. We store the results in a vector called days_total.
3. We now have a new vector which contains daily portfolio value totals. But it is not a part
of the portfolio_value matrix. We can add the days_total vector to the main matrix
using cbind() function.
4. Since we have the portfolio values over a three day period, we can calculate the average
portfolio value during this period. The values are in columns so we can
use colMeans() function to calculate the column means. We store these values in a
vector called days_average.
36 [Link]
5. Finaly we can add the days_average vector as a new row to our main matrix. Since we
are adding a row, we will use rbind() function.
6. The resulting matrix contains portfolio values along with totals and average over a period
of three days.
price_matrix
Bond Stock
Mon 64 31
Tue 65 28
Wed 66 35
# You hold 5 quantity each of bond and stock. What is the value?
days_total
# We can added the days_total vector to the main matrix using cbind()
final_matrix <-rbind(portfolio_value_totals,days_average)
# print final_matrix
final_matrix
37 [Link]
Bond Stock days_total
Mon 320 155.0000 475.0000
Tue 325 140.0000 465.0000
Wed 330 175.0000 505.0000
days_average 325 156.6667 481.6667
price_matrix
quantities <-c(5,3)
• diag() create a diagnal matrix from the vector so that we can then multiply the two
matrices.
• Multiplying the price matrix with the quantity vector will look as follows:
38 [Link]
The resulting matrix will look as follows:
portfolio_value
[,1] [,2]
Mon 320 93
Tue 325 84
Wed 330 105
Workspace
When you create a new vector, matrix or any other R object, it gets saved into the workspace
and is available for you to use in your calculations. These variables can be seen in the Global
Environment, i.e., the top-right window in RStudio. You can also access all objects available in
the workspace using the ls() command in R console.
ls()
39 [Link]
Factors in R Programming
In R programming, factors are variables that take on a limited number of different values.
Factors are used to represent categorical data.
• A common example of a factor is gender, which can have category values as Male and
Female.
• A data field such as marital status may contain only values from single, married,
separated, divorced, or widowed.
• For stocks, we can have them categorized as Large-cap, Mid-cap, and Small-cap
In R, the function factor() is used to encode a vector as a factor. In the following example, we
first create a vector which for this example categorizes stocks as Large-cap, Mid-cap, and
Small-cap. And then we use the factor() function to encode this vector as a factor.
stock_factor
When you print this vector, the results will look as follows:
stock_factor
40 [Link]
Levels and Order
When you print the factor, you can see that it also prints the Levels. By default, the levels are
sorted based on their character value. However, you can change the order in which the levels
will be displayed from their default sorted order, the levels= argument can be given a vector of
all the possible values of the variable in the order you desire.
Factors can be unordered or ordered. For example, we can consider the gender factor (Male
and Female) to be an unordered factor as it is not important which ones come first. However,
some other categories may have an order associated with them, for example, in our stock factor
we may want to have them ordered as per their market capitalization (Mid-cap being the
smallest and large-cap being the largest). If the ordering should also be used when performing
comparisons, use the optional ordered=TRUE argument. In this case, the factor is known as an
ordered factor.
We can now update our factor to have pre-defined levels and set the order to TRUE.
stock_factor
Changing Levels
Sometimes, you may have a factor with values in it and you may want to change the names of
those levels for more clarity or for relating it to something else in your model. In R, you can do
so using the levels() function. Let's say that our original factor contained letters L, M and S to
represent the three types of stocks. We can change the levels to Large-cap, Mid-cap and Small-
cap using the levels() function.
41 [Link]
# Convert the stock vector to a factor
stock_factor
In the results, you will have new levels applied to the factor.
stock_factor
Summarize a Factor
We can use the summarize() function to summarize the contents of the factor variable. As you
can see, it prints a quick snapshot of how many stocks you have of each type in your portfolio.
# Summarize stock_factor
summary(stock_factor)
42 [Link]
Let's say you have five stock traders in your team, and you have their performance evaluated
as "Poor", "Average", and "Good". The following R script shows how we can compare the
performances of these traders.
performance_factor
# Summarize stock_factor
summary(performance_factor)
[1] TRUE
Note that if the factor was not ordered this comparison would not work. It will give you a warning
message that comparison operator '>' is not meaningful. However, once you set
the ordered=TRUE, it will recognize the comparison operator.
43 [Link]
Statistical Modelling
One of the most important uses of factors is in statistical modeling. Since categorical variables
enter into statistical models differently than continuous variables, storing data as factors insures
that the modeling functions will treat such data correctly. (Note: Categorical variables are
different from continuous variables in that a categorical variable can take on a limited number of
categories while a continuous variable can have an infinite number of values.)
I hope you found this book useful. Please also checkout our eBook on Quantitative Trading
Strategies with R.
Link: [Link]
END
44 [Link]