0% found this document useful (0 votes)
5 views44 pages

Getting Started With R Programming

This document is an introductory guide to R programming, focusing on its application in finance. It covers installation procedures for R and RStudio, basic arithmetic operations, and the use of variables, including how to set up a working directory. The guide aims to equip finance professionals with essential R programming skills for data analysis.

Uploaded by

deepika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Getting Started With R Programming

This document is an introductory guide to R programming, focusing on its application in finance. It covers installation procedures for R and RStudio, basic arithmetic operations, and the use of variables, including how to set up a working directory. The guide aims to equip finance professionals with essential R programming skills for data analysis.

Uploaded by

deepika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Getting Started

with
R Programming

Copyright © 2022 Finance Train

All Rights Reserved


[Link]
Introduction

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.

Installing R Software on Your Computer

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.

Step 1: Download Software

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

Download R for Windows

1. Under “Download and Install R”, click on the “Windows” link.


2. Under “Subdirectories”, click on the “base” link.
3. On the next page, you should see a link saying something like “Download R 3.3.2 for
Windows” (or R X.X.X, where X.X.X gives the version of R, eg. R 3.3.2). Click on this
link.
4. You may be asked if you want to save or run a file “[Link]”. Choose “Save”
and save the file on the Desktop.

Download R for Mac

1. Under “Download and Install R”, click on the “Mac” link.


2. On the next page, under filesyou should see a link saying something like “R-
[Link]” (or R X.X.X, where X.X.X gives the version of R, eg. R 3.3.2). Click on this
link.
3. You may be asked if you want to save or run a file “[Link]”. Choose “Save” and
save the file on the Desktop.

Step 2: Install the Software

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.

Performing Basic Math Operations in R

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.

Consider the following arithmetic operators:

• 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.

• Type 5-3 in the R console to calculate the difference between 5 and 3.

• Type 5*3 in the R console to calculate the product of 5 and 3.

• Type 5/3 in the R console to divide 5 by 3

• Type 3^5 in the editor to calculate 3 to the power 5.

• Type 26 %% 3 to calculate 26 modulo 3.

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

In this ebook, all code comments are colored purple.

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.

# Set the working directory

setwd("C:/r-programming/data")

All R code is colored black.

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.

An example for Mac:

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"

All results are colored green.

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"

.. means the parent directory, so it goes one level up there

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.

It is preferred to download Installers rather than Zip/Tarballs or Source Code.

Click the relevant file and the download will begin.

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:

• CTRL+L to clear the console

• 3+5 to calculate the sum of 3 and 5

• 26%%3 to calculate the 26 modulo 3.

Your RStudio screen should now look something like this:

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.

Let’s take a look at the RStudio screen and how it is organized.

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.

# Assignment using equal operator.

x = 50

# Assignment using leftward operator.

y <- "table"

# Assignment using rightward operator.

100 -> z

print (x)

cat ("x is ", x ,"\n")


cat ("y is ", y ,"\n")

13 [Link]
cat ("z is ", z ,"\n")

When executed, this will produce the following result:

[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.

Arithmetic Operations Using Variables


Once you have assigned variables, you can use these variables to perform arithmetic
operations. Let’s say you have 5 Google stocks in your stock portfolio and 7 Microsoft stocks.

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.

# Assign a value to GOOG and MSFT

GOOG <- 5

MSFT <- 7

# Add the two variables to get the total stocks in the portfolio

14 [Link]
GOOG + MSFT

# Assign the total to a new variable

TOTALSTOCKS = 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.

To test this, try running the following code in RStudio:

# Assign a value to GOOG and MSFT

GOOG <- 5

MSFT <- 'stock'

# 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

Let's briefly look at each of these.

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.

# Assign a decimal value to x

x <- 8.5

# Print the value of x

[1] 8.5

# Print the class name of x

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.

# Assign a value to a variable

x <- 8

# Check the class type of x

class(x)

[1] "numeric"

# You will notice that it is numeric.

# Use the [Link]() function to create an integer

y <- [Link](8)

# Check the class type of yx

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>.

# Assign a complex value to a variable

x = 1 + 2i

# Print the complex value x

[1] 1+2i

# Print the class of x

class(x)

[1] "complex"

Logical

Logical values are boolen values (TRUE or FALSE) often created by comparison between
variables.

# Create sample variables

x <- 5
y <- 7

# Check if y is less than x

z <- y < x

# z will have a logical value. Let's print it

[1] FALSE

# Print the class of z

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.

# Create a character variable

x <-"John Doe"

# Print the character string

[1] "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.

# Create a numeric variable

x <- 8.75

# Print the variable x

[1] 8.75

# Print the class of x

class(x)

[1] "numeric"

#convert x into a character value

y <- [Link](x)

# Print the variable y

20 [Link]
[1] "8.75"

# Print the class of y

class(y)

[1] "character"

Standard Logical Operations


We can perform standard logical operations such as "&" (and), "|" (or), and "!" (negation) on
logical values in R.

x = TRUE; y = FALSE

x & y # Checks that both x AND y are true

[1] FALSE

x | y # Checks that either x OR y is true

[1] TRUE

!x # Returns the negation of x

[1] FALSE

Standard String Operations


We can easily perform basic string operations in R such as concatenation, or creating readable
strings.

# Define sample character variables

fname <- "John"

21 [Link]
lname <- 'Doe'

# Concatenate strings using paste function

paste(fname, lname)

[1] "John Doe"

# Create a readable string using sprintf() function


# Use %s for strings and %d for numeric values

sprintf("His first name is %s and last name is %s",fname,lname)

[1] "His first name is John and last name is Doe"

# Extract a substr from a long string. In the following example, we


# are extracting stock symbol from text

substr("Google's stock symbol is GOOG", start=26, stop=29)

[1] "GOOG"

#Replace the first occurance of a word in a string by another word.

sub("John","Sam","His first name is John")

[1] "His first name is Sam"

The sprintf() function allows you to create strings as output using formatted data. For example:

sprintf("I go for a walk at %s:%s%s a.m.", 7, 0, 5)

# The followinhg will output:

[1] "I go for a walk at 7:05 a.m."

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).

Creating and Using Vectors in R

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.

# John's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

# Ivan's earnings in the week.

23 [Link]
ivan_earnings <- c(-30,-60,80,-250,200)

# Print John's earnings

john_earnings

# Print Ivan's earnings

ivan_earnings

Run this script in RStudio (CTRL+ENTER) and you will see the results in RConsole.

# John's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

# Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

# Print John's earnings

john_earnings

[1] 120 -40 25 -130 260

# Print Ivan's earnings

ivan_earnings

[1] 120 -40 25 -130 260

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.

#John's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

#Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

#Calculate total earnings

total_earnings_per_day = john_earnings + ivan_earnings

#Print total earnings

total_earnings_per_day

Run this script in your computer and compare the results with the ones below:

#Print Ivan's earnings

total_earnings_per_day

[1] 90 -100 105 -380 460

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.

# John's earnings in the week

25 [Link]
john_earnings <- c(120,-40,25,-130,260)

# Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

# Calculate John's total earnings for the week

john_total <- sum(john_earnings)

# Calculate Ivan's total earnings for the week

ivan_total <- sum(ivan_earnings)


# Calculate total combined earnings for the week

total_earnings <- john_total + ivan_total

# Print individual totals and combined total

john_total

ivan_total

total_earnings

Run this script in your computer and compare the results with the ones below:

# Print individual totals and combined total

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's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

# Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

# Check if John performed better than Ivan each day

john_vs_ivan <- john_earnings > ivan_earnings

# Calculate John's total earnings for the week

john_total <- sum(john_earnings)

# Calculate Ivan's total earnings for the week

ivan_total <- sum(ivan_earnings)

# Check if John performed better than Ivan overall

overall_perfromance <- john_total > ivan_total

# Print John's performance vis-a-vis Ivan's each day

john_vs_ivan

# Print overall performance

overall_perfromance

27 [Link]
The results should match our visual understanding of the numbers:

# Print John's performance vis-a-vis Ivan's each day

john_vs_ivan

[1] TRUE TRUE FALSE TRUE TRUE

# Print overall performance

overall_perfromance

[1] TRUE

Other Arithmetic Operations


Just like addition we can perform all arithmetic operations on vectors such as subtraction,
multiplication, and division. The following example shows the difference between John's and
Ivan's earnings each day.

# John's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

# Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

# Calculate difference in earnings

difference <- john_earnings - ivan_earnings

# Print the difference

Difference

The results will be as follows:

# Print the 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's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

# Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

# Select John's earnings on 3rd day

john_earnings[3]

[1] 25

# Select John's earnings on 2nd and 5th day


# You can select multiple values by supplying a vector of indexes

john_earnings[c(2,5)]

[1] -40 260

# Select John's earnings from 2nd to 4th day


# To produce a vector slice between two indexes,
# you can use the colon operator ":". Helpful for large vectors.

john_earnings[2:4]

[1] -40 25 -130

Naming Vector Members


We learned how to refer to the elements of the vector but it's still difficult to tell which earnings
belong to which day. In such situations, we can assign names to the members of the vectors. In
our case, we can assign the names of days to the elements. We can do so by using
the names() function as shown below:

29 [Link]
# John's earnings in the week

john_earnings <- c(120,-40,25,-130,260)

#Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

# Assign the names of the day to John's Earnings vector

names(john_earnings) <- c("Monday", "Tuesday", "Wednesday", "Thursday",


"Friday")

#If you're applying these names to multiple vectors, you can even
#create a new vector with these names and then assign it.

days_in_week <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

#Assign the names of the day to Ivan's Earnings vector

names(ivan_earnings) <- days_in_week

# Print John's and Ivan's earnings

john_earnings

ivan_earnings

Results will now look like below:

# Print John's and Ivan's earnings

john_earnings

Monday Tuesday Wednesday Thursday Friday


120 -40 25 -130 260
ivan_earnings

Monday Tuesday Wednesday Thursday Friday


-30 -60 80 -250 200

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

#John’s earnings in the week

john_earnings <- c(120,-40,25,-130,260)

#Ivan's earnings in the week

ivan_earnings <- c(-30,-60,80,-250,200)

#Total Earnings

total_earnings <- john_earnings + ivan_earnings

#Vector for days in week

days_in_week <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

#Assign the names of the day to Total Earnings vector

names(total_earnings) <- days_in_week

#On which days did we have positive earnings


#To do so we use comparison operators on vectors. The comparison operator
#will compare each element in the vector if the condition stated by the
#comparison operator is TRUE or FALSE

positive_vector <- total_earnings > 0

#Print the positive_vector

positive_vector

31 [Link]
Step 2 is to use the positive selection vector to slice the positive earnings
from total_earnings vector.

#Select the positive earing days from the total_earnings vector

positive_earning_days <- total_earnings[positive_vector]

#Print the positive earnings days

positive_earning_days

Monday Wednesday Friday

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:

price_data <- c(64,31,65,28,66,35)

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_data <- c(64,31,65,28,66,35)

# Create matrix of prices

price_matrix <- matrix(price_data, nrow=3,byrow=TRUE)

# Print the matrix

price_matrix

Matrix function parameters:

• 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.

• The third argument byrow indicates how the data should be


processed. byrow=TRUE indicates that it should be processed by row, i.e., as data
comes in it will first fill the first row, then second and so on. To process data by
columns, byrow should be set to FALSE.

When this matrix is printed, it will look as follows:

price_matrix

[,1] [,2]

33 [Link]
[1,] 64 31
[2,] 65 28
[3,] 66 35

Naming Rows and Columns


Currently our matrix doesn't have any names for the rows and columns and it's difficult to
understand the data. Our first column represents the prices of the bond and the second column
represents the prices of stock. The three rows represent three days, namely, Mon, Tue and
Wed.

In R, we can assign names to the matrix using the rownames() and colnames() functions as
shown below:

#set row names and column names for price_matrix

rownames(price_matrix) <- c("Mon","Tue", "Wed")

colnames(price_matrix) <- c("Bond","Stock")

#print the matrix

price_matrix

We can now print the 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

dimnames(price_matrix) <-list(c("Mon","Tue", "Wed"),c("Bond","Stock"))

# Print the matrix

price_matrix

Selecting the Matrix Elements


We can select specific elements of a matrix by using the expression D[m, n], i.e., mth row and
nth column of matrix D.

Below R script shows some different ways of selecting the matrix elements:

# Print the matrix

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

# Get me just the stock prices for all days


# In this case we want to access all rows, so we will just omit supplying the
row
# Stock prices are in 2nd column

price_matrix[,2]

Mon Tue Wed


31 28 35

# Get stock and bond price on Tuesday


# Tuesday is the 2nd row

price_matrix[2,]

35 [Link]
Bond Stock
65 28

# Get all prices for Monday and Wednesday


# Monday and Wednesday data is in row 1 and 3

price_matrix[c(1,3),]

Bond Stock
Mon 64 31
Wed 66 35

# Get stock prices for Tuesday and Wednesday


# We can use colon for continuing elements

price_matrix[2:3,2]

Tue Wed
28 35

Arithmetic Operations on Matrices


Just like vectors, we can use standard operators +, -, /, * with matrices. Let's take a few
examples to understand the matrix arithmetic and also understand a few other matrix
operations along the way.

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.

# Print the matrix

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?

portfolio_value <- price_matrix * 5

# What is the total portfolio value on each day

days_total <- rowSums(portfolio_value)

# Print days total

days_total

Mon Tue Wed


475 465 505

# We can added the days_total vector to the main matrix using cbind()

portfolio_value_totals <- cbind(portfolio_value,days_total)

# Calculate average value per day

days_average <- colMeans(portfolio_value_totals)

# Add the averages row to the portfolio_value_totals matrix

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

Multiplying Matrix with a Vector


In the above example, we assumed the same quantity 5 for both stock and bond and simply
multiplied it with the matrix. R took care of multiplying each matrix element with 5 to get us the
values. However, what if we have different quantities of stock and bond. In such a case we can
store the quantities in a new vector and then do standard matrix multiplication to achieve our
results. Note that what we did earlier (multiply by *) is not the standard matrix multiplication for
which you should use %*% in R. The calculation and nuances are demonstrated below:

# Print the matrix

price_matrix

# Assign quantities - 5 bonds and 3 stocks

quantities <-c(5,3)

# Multiply prices with quantities to get the values.

portfolio_value <- price_matrix %*% diag(quantities)

• %*% represents standard matrix multiplication.

• 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.

Using ls() command:

ls()

[1] "days_average" "days_total" "final_matrix"


[4] "portfolio_value" "portfolio_value_totals" "price_data"
[7] "price_matrix"

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.

Some examples of factors:

• 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.

# The following vector classifies 5 stocks

stock_vector <- c("large-cap","small-cap","large-cap","mid-cap","small-cap")

# Convert the stock vector to a factor

stock_factor <- factor(stock_vector)

# Print the stock_factor

stock_factor

When you print this vector, the results will look as follows:

stock_factor

[1] large-cap small-cap large-cap mid-cap small-cap


Levels: large-cap mid-cap small-cap

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.

# Convert the stock vector to a factor

stock_factor <- factor(stock_vector, ordered=TRUE, levels=c("small-cap",


"mid-cap", "large-cap"))

# Print the stock_factor

stock_factor

[1] large-cap small-cap large-cap mid-cap small-cap


Levels: small-cap < mid-cap < large-cap

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.

# The following vector classifies 5 stocks

stock_vector <- c("L","S","L","M","S")

41 [Link]
# Convert the stock vector to a factor

stock_factor <- factor(stock_vector, ordered=TRUE, levels=c("S","M","L"))

levels(stock_factor) <- c("small-cap", "mid-cap", "large-cap")

# Print the stock_factor

stock_factor

In the results, you will have new levels applied to the factor.

# Print the stock_factor

stock_factor

[1] large-cap small-cap large-cap mid-cap small-cap


Levels: small-cap < mid-cap < large-cap

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)

small-cap mid-cap large-cap


2 1 2

Use of Ordered Factor


In R the most apparent effect of using ordered vs. unordered factor is in pretty printing of the
output. Apart from this, ordering and levels can be important in linear modelling because the
first level is used as the baseline level. We will learn about these use cases when we learn
linear modelling, however, here we will take a simple example to understand the use of
ordering.

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.

# The following vector classifies 5 stocks

performance_vector <- c("Good","Average","Poor","Poor","Good")

# Convert the stock vector to a factor

performance_factor <- factor(performance_vector, ordered=TRUE,


levels=c("Poor","Average","Good"))

# Print the stock_factor

performance_factor

[1] Good Average Poor Poor Good


Levels: Poor < Average < Good

# Summarize stock_factor

summary(performance_factor)

Poor Average Good


2 1 2

# Performance value of 2nd and 4th trader

pv2 <- performance_factor[2]


pv4 <- performance_factor[4]

# Is trader 2 better than trader 4?

pv2 > pv4

[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.)

Note from Finance Train

I hope you found this book useful. Please also checkout our eBook on Quantitative Trading
Strategies with R.

Link: [Link]

END

44 [Link]

You might also like