Introduction to R for undergraduates in economics

Daniel Leppert

R is a programming language and free software environment for statistical computing and graphics supported by the R Foundation for Statistical Computing. The R language is widely used among statisticians and data analysts for developing statistical software and data analysis. Together with Stata, R is the most commonly used programming language among academic economists today. One big advantage R has over Stata or SPSS is that it is open-source and requires no expensive license to use. This means that it is more widely used for doing statistics in industry, and you will continue to benefit from learning it after leaving university. Another advantage of R is its wealth of associated packages including all kinds of additional functionality. R provides support for machine learning, geographic information systems, and scientific illustration and data visualisation.

Installing R

To install R on your personal computer, go to https://www.r-project.org/ and follow the instructions for your operating system. R is available for MacOS, Windows, and UNIX. Follow the links to the mirror closest to your geographic location. If you're residing in the UK, I suggest that you download a UK mirror, for example https://cran.ma.imperial.ac.uk/.

Installing RStudio

To program conveniently in R, you will need an IDE (Integrated Development Environment). The IDE you will use for R is RStudio. Once you have R installed on your machine, go to https://rstudio.com/products/rstudio/ and install the Desktop version. This is also free. RStudio comes with a workspace which makes it easier to manage your R code files and data, a debugger, and a customizable interface. It also comes with an interface to help you keep track of plots and packages. Upon first opening RStudio you should see something like the image below. Here I have an .R-file named 'intro', which is where I write my code. Once a piece of code is run, the output - e.g. printing 'Hello, World!' to the screen - is displayed in the console below. To the right, you see the environment window, where data and variables will be stored.

r_intro.png

Running R on AppsAnywhere (Durham students)

As current Durham University students, you can also access R and RStudio virtually via AppsAnywhere. Go to https://appsanywhere.durham.ac.uk/login and login using your Durham ID and password.

R Basics

Below is a very brief introduction to help you get started with the basics in R. However, there is an almost endless toolkit to learn to truly master the language, so I will link to some more detailed resources at the end. My advice to students is that whenever you face an exercise in your modules which asks you to compute something, work with data, or perform some statistical analysis, try to do it in R or your programming language of choice. By the time you graduate you will be much more comfortable with coding in general.

1. Variable assignment

In R, as with most programming, we want to simplify computation by storing the values we use in variables that we can refer back to, rather than re-writing them every time. This also makes it easier to keep track of what the code does. To create the variable zero and assign it the value 0, we write:

a <- b means that b is stored in a. Now whenever we write zero, R will remember that this means the value 0. We can also do arithmetic using variables:

2. Functions

Functions in R are much the same as in mathematics. They are pre-programmed code that takes an input, performs a given operation, and spits out an output. Eventually you will learn to write your own custom functions, but we stick to functions already within base R for now. A function is recognized by its name followed by a parenthesis. The input goes within the parenthesis. In RStudio, you can type ?'function name' in the command line to get further information about the function:

Description

Generic function for the (trimmed) arithmetic mean.

Usage

3. Data structures

Data structures are really just what they sound like: They describe how data objects are structured. R terminology is similar to what you have encountered in algebra in this respect. One-dimensional data is a vector, two-dimensional data is a matrix, and multidimensional (D>2) data are called arrays. We can create data structures by combining existing data

the cbind() function combines the two vectors of length = 2 into a two-by-two matrix. The horizontal sequences in a matrix are called rows, and the vertical sequences are called columns. Hence, cbind() is just short for column-bind. Similarly there is rbind() to combine rows horizontally. We can create data structures by combinining existing data like this, but we can also create new custom, empty data and fill them later:

We populate the first 2x2 in array with the 2x2 matrix, and the second 2x2 with the transpose of the matrix.

You will see that the array is simply storing the values of each matrix one after the other. As such arrays are the primary method to store higher dimensional data. The notation also provides a simple way to quickly retrieve data from a data object. For example, if I want to see what value is stored in the second row of the first column in Matrix:

4. For-loops and If-statements

Often we want to perform a given set of operations on multiple variables. In such cases it is not convenient to rewrite the code in every instance. Here is where for-loops come in handy. They allow us to loop an operation over several variables or elements in a data structure. If-statements allow us to specify conditions to the operations in the loop. For example, we may want to print every positive value in a vector. We also print a warning whenever the value is negative.

The condition is written inside the parantheses, followed by the conditional operation inside curly brackets. Conditions are expressed as so-called Boolean operators:

4. Classes

Any value within any kind of data structure will have a class. It is important to know about classes because not all operations within R can be performed on all classes. Three classes that you will encounter frequently are 'numeric', 'character' and 'date'. You can get the class of an object by giving it as the input in the function class()

The value in the first row of the first column of matrix is numeric. It's 0. However, if we want, we can combine different classes in the same data structure. The most common way to do so is with the data frame. This is basically a table. Below we set up a table containing the names of students (curiously named after famous British economists) and the module they take:

We also have a table of the marks awarded for each module:

We see that the MODULE variable has class 'character', while the grade variables have class 'numeric. You can, for example, perform arithmetic operations on numeric data, but not on character data.

The merge() function

An important function for working with data.frames is the merge() function. This allows us to combine multiple tables by merging a common variable name. Let's merge the two tables 'students' and 'marks' to find out the mark earned by each student.

by = 'MODULE' means that we merge based on the common variable 'MODULE' in the two tables. If we know what the grade was in each module, and which student took each module, we also know which grade each student got. Merge is a very valueble tool for working with multiple datasets. As economists, we often need to combine data from multiple sources, and in these cases we frequently combine data based on common identifying variables.

Now we can use a for-loop and the mean function to get the average mark of each student. We can also use an if-statement to show that a student achieved a 1st Class if they got an average mark of 70 or above:

Plotting

If we want to visualize our data, R offers functionality for that too. To make pretty plots, we want to install and load the package 'ggplot2' which is used to produce publication-quality graphs and figures.

Further reading

This document was meant to provide the basics to equip you to do simple exercises like the Economics of Sustainability seminar questions in R. However there is much more to learn. Below I list some good resources:

'Introduction to Statistical Learning with Applications in R' by James, Witten, Hastie and Tibshirani. 2013

A highly recommended textbook introducing statistical analysis and machine learning with R. Also comes in a more advanced version 'Elements in Statistical Learning'.

https://cran.r-project.org/doc/manuals/r-release/R-intro.pdf and https://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf

A free manual to R from the core R development team. A much more in-depth version of this document.

http://www.sthda.com/english/wiki/be-awesome-in-ggplot2-a-practical-guide-to-be-highly-effective-r-software-and-data-visualization

A practical guide to ggplot - learn to make highly AESTHETIC figures and graphs!