0% found this document useful (0 votes)
2 views14 pages

Session 2 - Practical 01 - Introduction to R

This document serves as an introduction to the R programming language, covering its basic functionalities, data manipulation, visualization, and statistical analysis. It highlights R's scalability, customizability, and open-source nature, while also addressing its learning curve. Key topics include reading data, summarizing datasets, data selection, data classes, plotting, and basic analytics.

Uploaded by

laseya.greenhill
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)
2 views14 pages

Session 2 - Practical 01 - Introduction to R

This document serves as an introduction to the R programming language, covering its basic functionalities, data manipulation, visualization, and statistical analysis. It highlights R's scalability, customizability, and open-source nature, while also addressing its learning curve. Key topics include reading data, summarizing datasets, data selection, data classes, plotting, and basic analytics.

Uploaded by

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

Session 1: Introduction to R

This section of the lecture notes aims to provide a quick overview of basic functionality of
the R software for statistical computing (R Core Team, 2014). It is intended to help the
analyst understand the basic structure and logic of the language and prepare him or her for
productive work with it.
The topics included range from an introduction into R through reading data and
manipulating data, visualizing it, and conducting statistical analyses. The text is
structured in a hands-on way and can be both read in its entirety or referred to on the go.

Introduction
The R language is a popular language for statistical programming, hailing from work on
the S language in the late twentieth century. Since then, R is supported by a large
community and continuously developed by a core team of programmers and statisticians.
It is popular among academics and researchers and is recently gaining popularity in
data-intensive businesses as well. For a more through introduction to the R language and
its applications, the reader is directed to Gareth et al. (2013) and to Bell (2020).
It is particularly notable for the following:

• Scalable - it scales well and can do analysis on large data sets - something that
traditional tools either cannot, or were slow to adapt

• Up-to-date - it includes the most novel statistical methods and approaches, that are
often not contained in proprietary software packages

• Customizable - it gives the user complete control over the processes

• Diverse - it provides numerous alternative ways to do particular analysis and


visualizations, letting users choose their preferred one

• Popular - it is widely used and supported by a large and enthusiastic community


that can be a source of help and inspiration

• Open-source and freeware - it is open-source which allows constant development


by non-members of the core team and is also free of charge, making it accessible to
large audiences.

Of course, this has to be taken against the steep learning curve and the sometimes
demanding system requirements (especially for RAM). Overall, the R language is a
versatile tool that can provide competitive advantage to those who master it and use it.

5
Reading-In Data
The rst part of an analysis is to actually read data in, that can be worked with. A
standard way is to have a source of data in some form and load it. If it is a table, one can
use the [Link] command. The program will try to nd the specied name in the
command in the home directory and load it. If it is not in the home directory, the user will
have to specify the full path.

[Link](file = "[Link]")

This command gives a lot of exibility as it has further options that can specify all details
needed - the header, the separator, column names, special symbols, etc. The best way to
understand a command is to write it over on the command line with a ? in front of it. This
will open the help le, giving more details about it, and concrete examples of usage and
syntax.

?[Link]

A simpler version of this is a command to read .csv les, which has less options and is
easier to use.

[Link]("[Link]")

If you only write this, the data will be read but not stored in the R environment. You have
to assign it to an object. The way to do this is to use the assignment operator <-.

data <- [Link]("[Link]")

In this way we create an object named data and assign it to contain the data that was read
into the le.
Another way to load data is to just use one of the datasets that comes in R itself and
perform analysis and visualization on it. To see what data is available type:

data()

For example we can load the data on closing prices of major European Stock market
indices over the period 1991-1998. This is done with the following command:

data(EuStockMarkets)

The data appears in the global environment and is ready to work with.

6
Summarizing Data
A common rst step is to look at a few numerical and visual summaries of data in order to
better understand its form, structure, and some information. To look at the rst lines of
the dataset you can do the following with the head command.

head(EuStockMarkets)

## DAX SMI CAC FTSE


## [1,] 1628.75 1678.1 1772.8 2443.6
## [2,] 1613.63 1688.5 1750.5 2460.2
## [3,] 1606.51 1678.6 1718.0 2448.2
## [4,] 1621.04 1684.1 1708.1 2470.4
## [5,] 1618.16 1686.6 1723.1 2484.7
## [6,] 1610.61 1671.6 1714.3 2466.8

And to look at the last lines, you can use the tail command:

tail(EuStockMarkets)

## DAX SMI CAC FTSE


## [1855,] 5598.32 7952.9 4041.9 5680.4
## [1856,] 5460.43 7721.3 3939.5 5587.6
## [1857,] 5285.78 7447.9 3846.0 5432.8
## [1858,] 5386.94 7607.5 3945.7 5462.2
## [1859,] 5355.03 7552.6 3951.7 5399.5
## [1860,] 5473.72 7676.3 3995.0 5455.0

General descriptive statistics can be obtained via the summary command :

summary(EuStockMarkets)

## DAX SMI CAC FTSE


## Min. :1402 Min. :1587 Min. :1611 Min. :2281
## 1st Qu.:1744 1st Qu.:2166 1st Qu.:1875 1st Qu.:2843
## Median :2141 Median :2796 Median :1992 Median :3247
## Mean :2531 Mean :3376 Mean :2228 Mean :3566
## 3rd Qu.:2722 3rd Qu.:3812 3rd Qu.:2274 3rd Qu.:3994
## Max. :6186 Max. :8412 Max. :4388 Max. :6179

7
Data Selection
A common task is to select only a subset of data to manipulate it. For example, we may be
interested in the mean or the standard deviation of only one of the four indices. A common
way to select (or subset) data is to use [x, y] after the nane of the data. Here x
correspond to the column number, and y to the row number. If we want to select all
columns or rows, we just put , instead of a number.
For example, to select the rst (column) of the four market indices, we can type
EuStockMarkets[,1]. If we want to select the rst row of data (observation), we can type:

EuStockMarkets[1,]

## DAX SMI CAC FTSE


## 1628.75 1678.10 1772.80 2443.60

Finally if we want to select the rst observation of the rst column, then it is:

EuStockMarkets[1,1]

## DAX
## 1628.75

If we want to select just a column (variable), like the rst index, the can use the “$” sign
and the name of this variable. Note that this is not applicable for objects formatted as
time series. Once a subset of data is selected, it can be assigned to an object in the R
environment. Here we assign the index FTSE to the ftse object:

FTSE <- EuStockMarkets[,4]

We can either use the object and apply functions to it, or use the selection straight away.
Here we calculate the mean (mean) and the standard deviation (sd) of the index:

mean(FTSE)

## [1] 3565.643

sd(FTSE)

## [1] 976.7155

Insted of the object we can also use the selection:

8
mean(EuStockMarkets[,4])

## [1] 3565.643

sd(EuStockMarkets[,4])

## [1] 976.7155

Data Classes
R supports many data classes that describe dierent types of data and that require
dierent analytic methods and have dierent visualization needs. Fortunately, a lot of
functions in R are generic, i.e. they check the type of data and nd the most appropriate
method for this data. Sometimes, however, it is useful to know the class of the data object
one works with, and sometimes it is imperative to be able to change it.
A few common types of data are:

• Numeric - quantitative values that can be processed through dierent analytics and
plotted. Example: asset prices.

• Character - a string of letter, usually a name, or some textual information.


Example: company names.

• Factor - an ordinal or nominal value that distinguishes between data categories.


Example: company sector.

• Time Series - numeric data that has a temporal dimension to it. Example: asset
returns on given days.

To understand what is the class of a given object or subset, we can use the class command,
and to get an idea of how the object is structured, we can use the str command” ”

class(EuStockMarkets[,1])

## [1] "ts"

str(EuStockMarkets[,1])

## Time-Series [1:1860] from 1991 to 1999: 1629 1614 1607 1621 1618 ...

9
Sometimes specic analytic or plotting methods require a dierent class of data that the
analyst may have. In this case data has to be coerced into the needed class. This is done
by using the [Link] command where XX refers to the new class of data. For example if we
want to coerce the time series object EuStockMarkets[,1] into numeric class and assign it to
object x we do the following:

DAX <- [Link](EuStockMarkets[,1])


class(DAX)

## [1] "numeric"

One should be careful what data class is required by a certain method and be careful that
the data class at hand and the required one are consistent. Lack of this can lead to either
errors or incorrect results.

Plotting Data
A key feature of any statistical language is its plotting facilities. Visualization of data helps
better understanding, enable the discovery of patterns and trends in data, and nally
makes for much better and clearer communication of results. The R language has many
alternative plotting facilities. The most basic one is the plot command. It is a generic
command which will produce a dierent default type of plot depending on the data at
hand. We can use it to plot the rst index of the EuStockMarkets data:

plot(EuStockMarkets[,1])

10
6000
EuStockMarkets[, 1]

4000
2000

1992 1993 1994 1995 1996 1997 1998

Time

We can customize color with the option col, change the line width with the option lwd
and the two axis names with the optiona xlab and ylab. The main title is set with the
option main, as follows:

plot(EuStockMarkets[,1], col="blue", lwd=2, ylab="Indev Value",


main = "DAX Dynamics over the period 1991-1999")

11
DAX Dynamics over the period 1991−1999
6000
Indev Value

4000
2000

1992 1993 1994 1995 1996 1997 1998

Time

There are many other options that can be explored with the ?plot command. Another
important graph would be the histrogram. We make a histrogram (hist) of the DAX
values as follows:

hist(EuStockMarkets[,1], col="blue", ylab="No. Observations", xlab = "DAX Value",


main = "Histogram of DAX Realizations")

12
Histogram of DAX Realizations
600
No. Observations

400
200
0

1000 2000 3000 4000 5000 6000

DAX Value

A useful type of graphic is the boxplot. We can see the comparative values of dierent
groups of observations using it. Here we the boxplot command to compare the four indices:

boxplot(EuStockMarkets, col="green",
main="Values of EU Stock Market Indices")

13
Values of EU Stock Market Indices
8000
6000
4000
2000

DAX SMI CAC FTSE

Finally, we can see how related are two pairs of indices using a scatterplot. For this
purpose we convert time series data into numeric data and assign them to two object - DAX
and FTSE:

DAX <- [Link](EuStockMarkets[,1])


FTSE <- [Link](EuStockMarkets[,4])

Now we use the scatterplot. Given this types of data it will be automatically generated by
the plot commnad, but we can also explicitly set using the option type in the command:

plot(DAX, FTSE, col="blue", main="DAX and FTSE Dynamics", cex=0.3)

14
DAX and FTSE Dynamics
3000 4000 5000 6000
FTSE

2000 3000 4000 5000 6000

DAX

Now that we have plotted them against each other we can see that they are move very
closely together, thus implying positive and relatively strong correlation between the two.
All the plot generated by the commands in R can be saved to disk using the [Link]()
command, followed by the [Link]() one.
The are numerous alternative graphic systems in R which also produce more visually
appealing graphs. The two leading contenders are Lattice graphs and the packages
ggplot2. They are also a bit harder to learn and tend to be somewhat less generic that
their more basic counterparts in the R language. However, a smooth transition to ggplot2
may be facilitated by the command qplot which is easy to use and customize. We
demonstrate the same scatterplot with it, and easily add a line of best bet (with smoother
option):

library(ggplot2)
qplot(DAX, FTSE, main="DAX and FTSE Dynamics", geom=c("point","smooth"),
alpha=I(0.05))

## ‘geom_smooth()‘ using method = ’gam’ and formula ’y ~ s(x, bs = "cs")’

15
DAX and FTSE Dynamics

6000

5000
FTSE

4000

3000

2000 3000 4000 5000 6000


DAX

Basic Analytics
The R language supports a wide range of statistical analyses that can provide insight into
data and help in the practical risk management process. Apart from the rich functionality
that comes with the base packages there are constantly new tools and techniques that are
being developed by the community.
Here we provide an overview of two basic but very common statistical operations. Once the
logic is apparent, it can esaily be transferred to other operations. It is often of interest to
quantitatively measure the correlation between variables in order to see the potential for
risk hedging. The basic command cor can help:

cor(DAX, FTSE)

## [1] 0.9751778

The high correlation between DAX and FTSE formalizes their close connection that was
already apparent in plotting. Linear regression is commonly used to observe the eect of
one independent variable (or many variables) over a dependent one. The command used
for it is ‘lm’ and R automatically prints output:

16
lm(DAX~FTSE)

##
## Call:
## lm(formula = DAX ~ FTSE)
##
## Coefficients:
## (Intercept) FTSE
## -1331.237 1.083

Alternatively, the analyst may choose to store the linear regression into and object and then
preview a summary of that. Apart from the convenience of storing results, the summary
command on the lm object will provide more information about the regression itself.

lm <- lm(DAX~FTSE)
summary(lm)

##
## Call:
## lm(formula = DAX ~ FTSE)
##
## Residuals:
## Min 1Q Median 3Q Max
## -408.43 -172.53 -45.71 137.68 989.96
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.331e+03 2.109e+01 -63.12 <2e-16 ***
## FTSE 1.083e+00 5.705e-03 189.84 <2e-16 ***
## ---
## Signif. codes: 0 ’***’ 0.001 ’**’ 0.01 ’*’ 0.05 ’.’ 0.1 ’ ’ 1
##
## Residual standard error: 240.3 on 1858 degrees of freedom
## Multiple R-squared: 0.951, Adjusted R-squared: 0.9509
## F-statistic: 3.604e+04 on 1 and 1858 DF, p-value: < 2.2e-16

It may be useful to extract the regression output for some purposes (e.g. if the coecients
are betas of interest). This is done by selecting the coef part of the regression summary
and writing it to a disk (e.g. by using the [Link] command). This will give you most of
the lm output (including coecients, constant, errors, t-statistics, and p-values) in simple
tabular from for further reuse or reporting.

17
[Link](summary(lm)$coef, "[Link]")

A lot of analytic commands follow this structure and logic but the user is recommended to
also have a look at their help pages using the ? command in order to gain greater insight
and ease of use.

Advanced Analytics and Expansion


Apart from the basic commands, the R statistical languages is characterized by a dazzling
variety of options, tools, and methods for covering the complete spectrum of analytic needs
- from the traditional classication and regression problems to the more novel ones such as
social network analysis.
Novel methods are usually found in packages - add-ons which are installed and loaded into
the basic R version. A lot of packages are hosted on CRAN where they are listed only after
passing a review for safety and operability. Every such package has a vignette which
describes the new commands it adds to R. Many of them come with specic examples.
Packages are installed via the [Link]() command. One of the packages that is
very well-suited to nancial analysis and risk management is the Performance Analytics
package. We install it, and then load it into R.

[Link]("PerformanceAnalytics")
library(PerformanceAnalytics)

After this operation is done, it can be used. More information can be obtained on the
package’s help section.

?PerformanceAnalytics

The versatility and adaptability of R, including through its ability to use


community-driven advanced analytics packages makes it an indispensable tool for the
modern RM and quantitative professional. Despite its steep learning curve, the R language
has many benets and unique advantages. It is also particularly suited for doing advanced
business analytics that have the key to unlock competitive advantages in today’s digital
economy (Bartlett, 2013; Sarker, 2021).

18

You might also like