Getting Started with R

A tutorial about data analysis using R (Website Version)

Author
Affiliation

Jon Yearsley

School of Biology and Environmental Science, UCD

Published

September, 2024


How to Read this Tutorial

This tutorial is a mixture of R code chunks and explanations of the code. The R code chunks will appear in boxes.

Below is an example of a chunk of R code:

# This is a chunk of R code. All text after a # symbol is a comment
# Set working directory using setwd() function
setwd('Enter the path to my working directory')

# Clear all variables in R's memory
rm(list=ls())    # Standard code to clear R's memory

Sometimes the output from running this R code will be displayed after the chunk of code.

Here is a chunk of code followed by the R output

2 + 4            # Use R to add two numbers
[1] 6

Objectives

The objectives of this tutorial are:

  1. Introduce R and RStudio
  2. Discuss online resources for help in using R
  3. Introduce the R console and command prompt
  4. Introduce R scripts

What is R?

R is powerful, open source software for data analysis. It has become the software of choice for analyzing data in research, industry, public bodies and beyond. R has a homepage at https://www.r-project.org with links to the software download site and R tutorials.

The internet is your friend: There are many sites on the internet offering discussion forums and tutorials in R.

Some good internet resources are:

What is RStudio?

We will always be using R from within RStudio.

RStudio is a program (https://www.rstudio.com) that provides a user friendly environment for R. RStudio will automatically start R (if R is installed on your computer). The basic RStudio desktop is free, works well, and simplifies many data analysis tasks with R.

Video Tutorial: A brief introduction to RStudio (2 mins)

Warning

When you open RStudio for the very first time you should go to the global setting (Tools -> Global Options) and:

  1. Set “Save workspace to .RData on exit” to Never.
  2. Uncheck the option “Restore .Rdata in workspace at startup

R’s console window

When you start RStudio (or R) for the first time you will see a window with a welcome message and the command prompt (>).

Figure 1: What you will see when you first open RStudio. The R console is on the left-hand side. RStudio looks very similar on all platforms.

The command prompt, >

The command prompt is a > symbol in R’s console window. This prompt is R’s way of saying “I’m waiting for your instructions to tell me what to do”.

Typing commands at a command prompt is called a command line interface.

When you start to use R the console window will have the following text

R is free software and comes with ABSOLUTELY NO WARRANTY.   
You are welcome to redistribute it under certain conditions.   
Type 'license()' or 'licence()' for distribution details.   
   
  Natural language support but running in an English locale   
   
R is a collaborative project with many contributors.   
Type 'contributors()' for more information and   
'citation()' on how to cite R or R packages in publications.   

Type 'demo()' for some demos, 'help()' for on-line help, or   
'help.start()' for an HTML browser interface to help.   
Type 'q()' to quit R.   
   
>    

And there at the bottom left is the command prompt, >, waiting for you to send your first command.

R’s command prompt works like this:

  1. You type a command at the command prompt and press the return key
  2. R interprets your command
  3. If R can understand the command then
    • R performs the calculations that the command specifies
    • R prints the result of its calculation in the console window underneath your original command
  4. If R cannot understand the command then you’ll receive an red error message

Why bother typing?

You are probably asking:

“Why are you asking me to use a program that requires typing the commands? Why don’t you teach a more user-friendly program with buttons to press and menus?”

the command line interface approach has three big advantages. It makes your data analysis:

  1. easily repeatable
  2. easily documented
  3. easily shareable

Being able to repeat, document and share your work is a big deal in both science and in the commercial world.

These three advantages are all captured by the R script

R Scripts

Note

An R script makes your analysis repeatable, well documented and shareable

Typing commands at the command prompt can quickly become tiring and error prone. R scripts are the solution.

An R script is a text file that contains

  • a set of R commands (these are intended for the computer to interpret)
  • accompanying comments (these are intended for humans to read)

The commands in an R script can be sent to R’s command prompt to be executed all at once.

The comments in an R script briefly explain the commands, explain the broader goal of the R script (e.g. logical sections like chapters of a book) and add structure to the script that makes it more readable.

An R script allows you to collaborate and communicate your data analysis methods, because it makes it easy to share, repeat and modify your data analysis.

Your first R script

Every R script should start with a short header which explains what the R script does, who wrote the script and when it was written.

Below is a header template you can use at the start of your own R scripts.

# ********** Start of header **************
# Title: <The title of your R script> 
#
# Add a short description of the R script here.
#
# Author: <your name>  (email address)
# Date: <today's date>
#
# *********** End of header ****************

# Two common commands at the start of an R script are:
rm(list=ls())         # Clear R's memory

setwd('~/DataModule') # Set the working directory 
# Replace '~/DataModule' with the name of your own directory

# ******************************************
# Write your commands below. 
# Remember to use comments to explain your commands

After the header you can start typing your commands.

Since R scripts contain only text they can be edited in any text editor (for example, notepad [PCs], textedit [macs] or gedit, nano [Linux]).

RStudio makes it very easy to send the commands in an R script into the R console. Here is a video explaining how this is done.

The # symbol

Note

The hash symbol, #, is the single most important character in R

The hash symbol, #, symbol allows you to annotate a R script by add a comment after the #.

Annotating your R scripts is important because:

  • it allows you to document what you are doing
  • it makes it easier for you to return to your work
  • it allows you to easily share your R scripts with others

All text appearing after the hash symbol is ignored by R. Text after the # is for you not R. The # can appear at the start of a line or it can appear after a command.

The R script template above is a good example of using annotation in an R script.

Practise using this important symbol by properly annotating your R scripts and seeing good practice in how others annotate their scripts.

RStudio allows comments to become section headings. The video below explains the basics of creating sections in an R script.

The working directory

Recommended Practice

The first command in an R script should set the working directory using the setwd() command.

R’s working directory is the directory on your computer where R will look for data files and save files. When you start R it will use its default for the working directory. Type the getwd() command at the command prompt to find out which directory this is.

getwd()          # Display the current working directory

The working directory can be changed using the setwd() command.

Setting the working directory

If you are using RStudio then you can use the Session -> Set Working Directory -> Choose Directory … menu set the working directory. This will send a setwd() command to the R console that you can copy into your R script.

Video Tutorial: Setting the working directory using RStudio (2 mins)

Help within R

R has built-in help pages. You can access help by typing ? followed by the name of the command.

?rm              # Display the help page for the rm command
?setwd           # Display the help page for the setwd command

Installing add-on packages

One powerful aspect of R is the ability to add functionality by loading packages. These packages must be installed and loaded before the functionality can be used in R. These are not loaded automatically because there are too many possible packages that are available to use.

Many of these packages are open source and written by academic researchers that are specialists in their field. A list of packages is maintained on the R website: https://cran.r-project.org/web/packages/

We will install three packages: ggplot2, reshape2 and tidyr

# Install the plotting package ggplot2, 
# reshape2 and tidyr (requires internet access)
install.packages('ggplot2')
install.packages('reshape2')
install.packages('tidyr')

Once a package has been installed on your computer it must be loaded each time you want to use it, using the library() command.

# Load the ggplot2 package 
# so that its functions are available for use
library('ggplot2')

The webpage for the ggplot2 package is https://ggplot2.tidyverse.org/

Closing R

Recommended practice before closing R
  1. Make sure you save all R scripts you have been working on
  2. Save important variables using the save() command (this command will be covered in the data import tutorial)
  3. When you close R you will be asked if you want to save the workspace. This is rarely useful.

Summary of topics

  • R and the R command prompt
  • R scripts and how to annotate them using comments
  • R’s working directory and how to set its value
  • Obtaining help in R
  • Using R as an advanced calculator
  • Exponential notation for large and small numbers
  • Variables
  • Missing data
  • R packages

Further Reading

All these books can be found in UCD’s library

  • Andrew P. Beckerman and Owen L. Petchey, 2012 Getting Started with R: An introduction for biologists (Oxford University Press, Oxford) [Chapter 1, 2]
  • Mark Gardner, 2012 Statistics for Ecologists Using R and Excel (Pelagic, Exeter) [Chapter 3]
  • Michael J. Crawley, 2015 Statistics : an introduction using R (John Wiley & Sons, Chichester) [Appendix]
  • Tenko Raykov and George A Marcoulides, 2013 Basic statistics: an introduction with R (Rowman and Littlefield, Plymouth)
  • John Verzani, 2005 Using R for introductory statistics (Chapman and Hall, London) [Chapter 1]