Introduction to R

Session 1

Session Overview

  1. What is R?
  2. First Steps in R
  3. What is RStudio?
  4. First Steps in RStudio
  5. R Script
  6. R Package Management System
  7. Inputs and Outputs

What is R?

What is R?

R

  • is an open-source statistical programming language.
  • available for most operating systems
  • helps users analyze, visualize, and model data—from simple summaries to complex data analysis
  • is extremely popular in statistics and data science, see this article
  • includes thousands of packages (add-ons) that can be used for specialized tasks without a deep understanding of the language and programming skills
  • allows for extensive programming, making it also suitable for advanced or case-specific applications of statistical methods

The combination of the latter two aspects sets R apart and makes it useful for everything ranging from standard ‘basic’ statistical analysis to the development of new methods.

The homepage of R is www.r-project.org from which you can install R and access manuals that provide detailed information about installing and using R.

First Steps in R

Opening R

Open R, you should see the following:

Opening R

The program window provides some basic information on R and the installed version.

Check your version of R!

R Console

The R Console can be used to directly give in commands and display output:

R Prompt

Under the default information, you can see the R prompt, through which R indicates that it is ready to execute a new command.

Executing your first command

Start by using R as a simple calculator, try to enter after the R prompt:

2+3

and hit enter.

You will see that R directly returns the output in the R console next to the ‘[1]’:

2+3
[1] 5

If you want to re-execute your previous command, use the arrow key . To make changes to a command, you can use the ←, → arrows and re-execute. To move to the next command, use the arrow.

Finally, when R receives an incomplete expression such as

2+

R will return the + symbol, thereby letting you know that you forgot to type something. You can either complete the command and then hit enter or exit the incomplete command via the esc button.

Exercise 1.1

Enter the following expressions, one by one, in R and hit enter to see how R evaluates them:

2 + 3*4

(2 + 3)*4

(2 + 3*4

sqrt(4)

pi

From R to Rstudio

After taking your first steps in R, you might not be impressed by the design of the user interface and the way the software is used.

There are various user interfaces that work on top of plain R to make it more user friendly. A very popular one is RStudio.

What is RStudio?

What is RStudio?

RStudio

  • is an Integrated Development Environment (IDE) for R

  • is a user-friendly interface for writing and running R code

  • makes it easier to write code, analyze data, create visuals, access documentation and manage projects

Its homepage is https://posit.co/download/rstudio-desktop/

First Steps in RStudio

Opening RStudio

Open RStudio, you should see the following:

Opening RStudio

You will recognize the R Console and see that RStudio is ready to receive input:

Exercise 1.2

Re-execute the commands you executed before in R now in the R Console of RStudio:

2 + 3*4

(2 + 3)*4

(2 + 3*4

sqrt(4)

pi

The console in RStudio behaves exactly the same as the plain R window!

Structure in RStudio

But RStudio has much more to offer than plain R!

RStudio (unlike R) is structured in different windows. You should currently see 3 windows:

  • Left: R console
  • Top right: Display of objects in the global environment
  • Bottom right: Files, plots, packages, help, etc.

RStudio Windows

The 3 main windows (aka panes) in RStudio:

RStudio Menu Bar

RStudio also has a Menu bar at the top:

The usefulness of these windows and menu bar in RStudio will become clear throughout this training.

Exercise 1.3

Explore the following quick tricks that the console in RStudio offers. After the prompt:

  • press the ctrl button on Windows, or the command on Mac together with the arrow key . What do you see?

It should give you a list of all previously executed commands. You can then use the and arrow keys to directly move to a certain command to repeat or correct it.

  • start to write sq and then hit the tabulator (tab) key right after without an additional space. What do you see?

It should present you with a list of suggested commands together with a short description. You can then use the and arrow keys to navigate through them. Which one is the relevant one to compute the square root of a number? Choose the appropriate function, then hit enter to compute the square root of 100.

Need for R Scripts

Suppose you want to continue your work tomorrow. If you would now close RStudio, all of your work would be gone!

To avoid this problem, we will not give commands directly in the R console, but save them in an R Script.

R Script

What is an R Script?

While many simple calculations can be done using the command line, as soon as things get more complicated, scripts should be used.

An R Script

  • is a plain text file that contains a collection of R commands

  • is written in such a form to perform commands in a step by step fashion

  • contains all commands including those for importing data, analyzing data, visualizing data or other tasks

  • can be saved as a .R file

  • allows you to automate and reproduce your work, allowing you to run the same analysis without having to redo each step manually again

  • makes your work organized, shareable and transparent!

Creating an R Script

Creating an R Script is easy.

Using the menu bar, go to File -> New File -> R Script:

Alternatively, you could have used the shortcut ctrl+shift+N on Windows or command+shift+N on Mac.

Structure in RStudio

RStudio now displays 4 windows, with the R Script currently displayed in the top left:

R Script

Currently the R Script is Untitled, we should give it a name.

Exercise 1.4

Give your R Script a name and save it. Go to File -> Save As…:

Exercise 1.5

Copy some of the commands you previously executed into your R Script.

Execute a specific line

  • by pressing the Run button to execute the line on which your cursor is currently located

  • by using ctrl+enter on Windows or command+enter on Mac to execute the line on which your cursor is currently located

You can execute multiple lines by highlighting them all and doing one of the above. Try this.

Exercise 1.6

You can adjust the sizes and positioning of the windows (panes) according to your liking.

Go to Tools, Global Options… and then select Pane Layout from which you can adjust the positioning of each of the 4 panes by selecting them from the drop-down menus

Experiment with a different positioning and re-adjust according to your liking.

R Package Management System

R Package Management System

Until now, we have explored some basic functionality in R. But much of the functionality of R is extended by its big and active community.

These extensions are called R packages

What are R packages?

R packages

  • are constantly developed and adjusted by the large user community making many state-of-the-art methods quickly available

  • can be installed for just about everything you want to do in statistics and data science

  • offer pre-defined functions which makes it possible to use R without a deep understanding of the language and programming skills.

Overview of R packages

The standard distribution of R comes already with a number of packages.

A list of the currently installed packages can be obtained from the Packages window in the bottom right window below

You can install new packages depending on your needs. We will explore R packages in much more detail in the upcoming sessions!

Input and Output

Inputs and outputs of your R session

  • Common inputs / outputs of an R session are datasets or R scripts.
  • For this meeting we focus on datasets as inputs to the R session, loading data and saving data.
  • The file format (csv, RData, xls, stata …) and directory of the files are important to keep in mind.
  • We will go over a few options, potential issues, and how to avoid the need to type in a long directory name when managing the input and output of the R session.

R Working Directory

Before we start working in our R Script, let us first set the working directory in R.

The working directory is the location on your computer where R will read and save files. Go to Session -> Set Working Directory. Two convenient options are:

  • Choose Directory…: Choose the directory yourself

  • To Source File Location: Set the working directory to the directory where your R Script (the source file) is saved

R Working Directory

Select the option to set the working directory to the source file location. You will see that a command automatically pops up in the R console, something like:

setwd("C:/Rtraining")

You can use this command directly next time. Mind the usage of the / when specifying the path of your working directory!

You can also include comment lines in your R script. These start with the symbol # and allow you to document your code. For instance:

# Setting my working directory
setwd("C:/Rtraining")

Finally, to retrieve your working directory you can use

R Working Directory

A very useful package to set your working directory in R is the package this.path. Install this R package.

To set the working directory to the folder where your current R script is located, you can simply use:

Input and Output Types

R interacts with files in several ways.

  • You can load, save, import, or export a data file.
  • You can save a generated figure as a graphics file or store regression tables as text, spreadsheet, or LATEX tables.
  • You can load, save the full workspace (environment) you are working with to follow up another time.

Datasets can come in different formats.

  • RData files: Files that can directly
  • Other file formats (SPSS csv, xls, …) are also possible to load in R. This often requires the use of packages

Loading RData files

  • RData files are specific to R file formats.
  • They can store a single object or several objects.
  • These files are the easiest to manage as input or output in R, since they don’t require library calls.

Loading RData files: Example

Download the data file climate_long.RData from the training website. Create a directory ‘data’ in your working directory. Save the Rdata file in this data directory.

You can now use the following lines of code to load your data and inspect it:

load("data/climate_long.Rdata")
print(long_data)
             NAME MONTH TEMP
99091   EINDHOVEN     1 10.6
99122   EINDHOVEN     2  7.1
99151   EINDHOVEN     3 10.2
99178   EINDHOVEN     4  8.9
99207   EINDHOVEN     5 18.5
99238   EINDHOVEN     6 15.0
99268   EINDHOVEN     7 15.0
99299   EINDHOVEN     8 20.7
99329   EINDHOVEN     9 22.6
99359   EINDHOVEN    10 10.0
99390   EINDHOVEN    11 10.5
99415   EINDHOVEN    12  9.7
99801  MAASTRICHT     1  9.7
99832  MAASTRICHT     2  5.9
99861  MAASTRICHT     3  9.9
99888  MAASTRICHT     4  9.0
99917  MAASTRICHT     5 15.7
99948  MAASTRICHT     6 14.1
99978  MAASTRICHT     7 14.9
100009 MAASTRICHT     8 20.5
100039 MAASTRICHT     9 21.6
100069 MAASTRICHT    10 10.3
100100 MAASTRICHT    11 10.2
100125 MAASTRICHT    12  9.2

The data is loaded as a dataframe (in long format), we will learn more about dataframes and formats in the next sessions.

Loading Other Formats of Data in R

We will explore how to import other data formats. First download the file climate_wide.xlsx from the training website.

Option 1: Using menus within RStudio is the easiest (click and go) but requires using the menu every time the user runs the code.

Loading Other Formats of Data in R

Option 1: Using menus within RStudio (cont’d)

Loading Other Formats of Data in R

Option 1: Using menus within RStudio (cont’d)

Loading Other Formats of Data in R

Option 1: Using menus within RStudio (cont’d)

Loading Other Formats of Data in R

Advice for option 1:

  • Copy the command that appears after loading the data from the menus.

Loading Other Formats of Data in R

Advice for option 1 (cont’d):

  • Paste the command on top of your script.
  • This way, next time you do not need the menu navigation.
  • Note that you need to install the package readxl to use its functionality.
library(readxl)
climate <- read_excel("data/climate_wide.xlsx")
  • You can view the data by clicking on it in the `Environment’ at the top-right of the workspace.

General Advice

  • Using the correct libraries for different data formats can be tedious.
  • R package rio is very convenient for data import and export. It figures out the type of data format from the file name extension, e.g. .csv for CSV, .dta for Stata, or *.sav for SPSS data sets
  • It calls an appropriate package to do the actual importing or exporting.

Exercise 1.7

  • Download the file climate.csv from the training website.
  • Save it in your data folder.
  • Install the R package rio.
  • Use the import function from the package rio to import the climate.csv file.
  • Inspect the data.

Loading data from APIs

  • It is possible to automatically load data from a web source using APIs.
  • An API (Application Programming Interface) acts as a bridge between your R code and an external data source: a website, database, or an online platform with permissions.
  • Advantages: Automation, efficiency and real-time access.
  • Disadvantages: No offline access to data (can be important for replication), dependency on external services (API can go down).
  • Suggestion: Save the downloaded data in RData format to mitigate disadvantages.

Loading data from APIs: Example

  • As an example we will download AAPL daily prices from Yahoo Finance.
  • Inspect the data
library(quantmod)
# Get Apple Inc. (AAPL) stock data from Yahoo Finance
getSymbols("AAPL", src = "yahoo", from = "2024-01-01", to = "2025-06-13")
# View the data
View(AAPL)

Outputs

  • Outputs work very similarly to the inputs above.
  • The most relevant outputs formats are the R output formats.
  • save() saves objects as an .RData file.
  • save.image() saves a selection of objects as an .RData file.

Exercise 1.8: Saving data

  • Save your current workspace using function save.image().
  • Save only one variable in the workspace using function save(). Save the AAPL data in your directory data.