Before we Start

Last updated on 2025-02-18 | Edit this page

Estimated time: 40 minutes

Overview

Questions

  • What is R and why learn it?
  • How to find your way around RStudio?
  • How to interact with R?
  • How to install packages?

Objectives

  • Navigate the RStudio interface.
  • Create an R project for project analysis.
  • Install additional packages using the packages tab.
  • Install additional packages using R code.

This episode is adapted from Before We Start from the R for Social Scientists Carpentry lesson, licensed under a Creative Commons Attribution 4.0 License (CC BY 4.0).

What is R? What is RStudio?


R is more of a programming language than just a statistics program. It was started by Robert Gentleman and Ross Ihaka from the University of Auckland in 1995. They described it as “a language for data analysis and graphics.” You can use R to create, import, and scrape data from the web; clean and reshape it; visualize it; run statistical analysis and modeling operations on it; text and data mine it; and much more. The term “R” is used to refer to both the programming language and the software that interprets the scripts written using it.

RStudio: a user interface for R

RStudio is a user interface for working with R. It is called an Integrated Development Environment (IDE): a piece of software that provides tools to make programming easier. RStudio acts as a sort of wrapper around the R language. You can use R without RStudio, but it’s much more limiting. RStudio makes it easier to import datasets, create and write scripts, and makes using R much more effective. RStudio is also free and open source. To function correctly, RStudio needs R and therefore both need to be installed on your computer.

Why learn R?


Two images of a DMC Delorian: left is a standard model and on the right is one that has been modified into the time machine from 'Back To The Future'
RStudio extends what R can do, and makes it easier to write R code and interact with R. Left photo credit; right photo credit.

R does not involve lots of pointing and clicking, and that’s a good thing.

The learning curve might be steeper than with other software, but with R, the results of your analysis do not rely on remembering a succession of pointing and clicking, but instead on a series of written commands, and that’s a good thing! So, if you want to redo your analysis because you collected more data, you don’t have to remember which button you clicked in which order to obtain your results; you just have to run your script again.

Working with scripts makes the steps you used in your analysis clear, and the code you write can be inspected by someone else who can give you feedback and spot mistakes. It forces you to have a deeper understanding of what you are doing, and facilitates your learning and comprehension of the methods you use.

R code is great for reproducibility.

Reproducibility is when someone else (including your future self) can obtain the same results from the same dataset when using the same analysis.

R integrates with other tools to generate manuscripts from your code. If you collect more data, or fix a mistake in your dataset, the figures and the statistical tests in your manuscript are updated automatically.

An increasing number of journals and funding agencies expect analyses to be reproducible, so knowing R will give you an edge with these requirements.

This focus on reproducibility not only helps ensure that your data adheres to the FAIR (Findable, Accessible, Interoperable, Reusable) principles but is also paving the way for software to become FAIR. As more researchers demand transparency and shareability, using R positions your code and analyses to be easily found, accessed, and reused by others.

R is interdisciplinary and extensible.

With 10,000+ packages that can be installed to extend its capabilities, R provides a framework that allows you to combine statistical approaches from many scientific disciplines to best suit the analytical framework you need to analyze your data. For instance, R has packages for image analysis, GIS, time series, population genetics, and a lot more.

R works on data of all shapes and sizes.

The skills you learn with R scale easily with the size of your dataset. Whether your dataset has hundreds or millions of lines, it won’t make much difference to you.

R is designed for data analysis. It comes with special data structures and data types that make handling of missing data and statistical factors convenient.

R can connect to spreadsheets, databases, and many other data formats, on your computer or on the web.

R produces high-quality graphics.

The plotting functionalities in R are endless, and allow you to adjust any aspect of your graph to convey most effectively the message from your data.

R has a large and welcoming community.

Thousands of people use R daily. Many of them are willing to help you through mailing lists and websites such as Stack Overflow, or on the RStudio community. Questions which are backed up with short, reproducible code snippets are more likely to attract knowledgeable responses.

Not only is R free, but it is also open-source and cross-platform.

R is also free and open source, distributed under the terms of the GNU General Public License.. This means it is free to download and use the software for any purpose, modify it, and share it. Anyone can inspect the source code to see how R works. Because of this transparency, there is less chance for mistakes, and if you (or someone else) find some, you can report and fix bugs. As a result, R users have created thousands of packages and software to enhance user experience and functionality.

Because R is open source and is supported by a large community of developers and users, there is a very large selection of third-party add-on packages which are freely available to extend R’s native capabilities.

Discussion: R for librarianship

For at least the last decade, librarians have been grappling with the ways that the “data deluge” affects our work on multiple levels–collection development, analyzing usage of the library website/space/collections, reference services, information literacy instruction, research support, accessing bibliographic metadata from third parties, and more.

Discuss some examples on how R or RStudio is useful for librarians.

  • Clean messy data from the ILS & vendors
    • Clean ISBNs, ISSNs, other identifiers
    • Detect data errors & anomalies
    • Normalize names (e.g. databases, ebooks, serials)
    • Create custom subsets
  • Merge and analyze data, e.g.
    • Holdings and usage data from the same vendor
    • Print book & ebook holdings
    • COUNTER statistics
    • Institutional data
  • Recode variables
  • Manipulate dates and times
  • Create visualizations
  • Provide data reference services
  • Access data via APIs, including Crossref, Unpaywall, ORCID, and Sherpa-ROMeO
  • Write documents to communicate findings

About RStudio


Let’s start by learning about RStudio, which is an Integrated Development Environment (IDE) for working with R.

The RStudio IDE open-source product is free under the Affero General Public License (AGPL) v3. The RStudio IDE is also available with a commercial license and priority email support from RStudio, Inc.

We will use the RStudio IDE to write code, navigate the files on our computer, inspect the variables we create, and visualize the plots we generate. RStudio can also be used for other things (e.g., version control, developing packages, writing Shiny apps) that we will not cover during the workshop.

One of the advantages of using RStudio is that all the information you need to write code is available in a single window. Additionally, RStudio provides many shortcuts, autocompletion, and highlighting for the major file types you use while developing in R. RStudio makes typing easier and less error-prone.

The RStudio Interface


Let’s take a quick tour of RStudio.

screenshot of RStudio with labels of the four panes as described below
R Studio

RStudio is divided into four “panes”. The placement of these panes and their content can be customized (see menu, Tools -> Global Options -> Pane Layout).

The Default Layout is:

  • Script Pane: This is sort of like a text editor, where you write and save a code. You can save the script as a .R file for future use and sharing, or run the code to generate an output.

  • Console Pane If you were just using the basic R interface, without RStudio, this is all you would see. The Console is where your scripts are executed. To execute a code, you can either run it from the Script Pane or type your code directly into the Console (you will see a blinking cursor > prompting you to enter some code.

  • Environment/History Pane: This will display the objects that you’ve read into what is called the “global environment.” When you read a file into R, or manually create an R object, it enters into the computer’s working memory. The History tab displays all commands that have been executed in the console.

  • Navigation Pane This pane has multiple functions:

    • Files: Navigate to files saved on your computer and in your working directory
    • Plots: View plots (e.g. charts and graphs) you have created
    • Packages: view add-on packages you have installed, or install new packages
    • Help: Read help pages for R functions
    • Viewer: View local web content

Tip: Saving your R code

To save your R codes and reuse them in the future, write and run your code from the Script Pane and save them as a .R file. This ensures your code is reproducible and that there is a complete record of what we did, and anyone (including our future selves) can easily replicate the results on their computer.

Alternatively, you can run temporary ‘test’ codes in the Console Pane – these will not be saved but are available in the History Pane.

Use the shortcuts Ctrl + 1 and Ctrl + 2 to jump between the Script and Console Panes.

Create a new project

RStudio project

An RStudio project (.Rproj) allows you to save all of the data, analyses, packages, etc. related to a specific analysis project into a single working directory.

All of the scripts within this folder can then use relative paths to files. Relative paths indicate where inside the project a file is located (as opposed to absolute paths, which point to where a file is on a specific computer).

Working this way makes it a lot easier to move your project around on your computer and share it with others without having to directly modify file paths in the individual scripts.

To create a new project, follow the instructions below.

  1. Under the File menu, click on New project.

  2. Select New directory, then New project.

  3. Enter your new project name e.g. my_project. This will be your working directory for the rest of the day.

  4. Finally, click on Create project. Create a new file where we will type our scripts. Go to File > New File > R script. Click the save icon on your toolbar and save your script as “script.R”.

Interacting with R


The basis of programming is that we write down instructions for the computer to follow, and then we tell the computer to follow those instructions. We write, or code, instructions in R because it is a common language that both the computer and we can understand.

There are two main ways of interacting with R: by using the console or by using script files (plain text files that contain your code). The console pane (in RStudio, the bottom left panel) is the place where commands written in the R language can be typed and executed immediately by the computer. It is also where the results will be shown for commands that have been executed. You can type commands directly into the console and press Enter to execute those commands, but they will be forgotten when you close the session.

The prompt

The prompt (>) is the blinking cursor in the console pane that prompts you to take action, in the lower-left corner of R Studio. If R is ready to accept a command, the R console shows a > prompt. If R receives a command (by typing, copy-pasting, or sent from the script editor using Ctrl + Enter), R will try to execute it and, when ready, will show the results and come back with a new > prompt to wait for new commands. We type commands into the prompt, and press the Enter key to evaluate (also called execute or run) those commands.

You can use R like a calculator:

R

2 + 2    # Type 2 + 2 in the console to run the command

Callout

Tip: Moving your cursor

In the console, you can press the up and down keys on your keyboard to cycle through previously executed commands.

Because we want our code and workflow to be reproducible, it is better to type the commands we want in the script editor and save the script. This way, there is a complete record of what we did, and anyone (including our future selves!) can easily replicate the results on their computer.

RStudio allows you to execute commands directly from the script editor by using the Ctrl + Enter shortcut (on Mac, Cmd + Return will work).

The command on the current line in the script (indicated by the cursor) or all of the commands in selected text will be sent to the console and executed when you press Ctrl + Enter. If there is information in the console you do not need anymore, you can clear it with Ctrl + L.

You can find other keyboard shortcuts in this RStudio cheatsheet about the RStudio IDE.

Tip: Incomplete commands

If R recognises that a command is incomplete, a + prompt will appear in the console. This means that R is still waiting for you to enter more text.

Usually, this occurs because you have not ‘closed’ a parenthesis or quotation. When this happens, click on the console and press Esc; this will cancel the incomplete command and return you to the > prompt. You can then proofread the command(s) you entered and correct the error.

Installing R packages


When you download R it already has a number of functions built in: these encompass what is called Base R. However, many R users write their own libraries of functions, package them together in R Packages, and provide them to the R community at no charge. Some examples include the dplyr and ggplot2 packages, which we will learn more in the coming chapters.

The CRAN repository

The Comprehensive R Archive Network (CRAN) is the main repository for R packages, and that organization maintains strict standards in order for a package to be listed–for example, it must include clear descriptions of the functions, and it must not track or tamper with the user’s R session.

See this page from RStudio for a good list of useful R packages. In addition to CRAN, R users can make their code and packages available from GitHub or Bioconductor (for computational biology and bioinformatics).


Installing packages using the Packages tab

Installing CRAN packages can be done from the Packages tab in the Navigation Pane. Click Install and type in the name of the package you’re looking for.

install packages pane showing an entry for installing the 'tidyverse' package
Click on the Packages tab in the Navigation Pane to download packages from CRAN.

At the bottom of the Install Packages window is a check box to ‘Install’ dependencies. This is ticked by default, which is usually what you want. Packages can (and do) make use of functionality built into other packages, so for the functionality contained in the package you are installing to work properly, there may be other packages which have to be installed with them. The ‘Install dependencies’ option makes sure that this happens.

Exercise

Use the install option from the packages tab to install the ‘tidyverse’ package.

From the packages tab, click ‘Install’ from the toolbar and type ‘tidyverse’ into the textbox, then click ‘install’. The ‘tidyverse’ package is really a package of packages, including ‘ggplot2’ and ‘dplyr’, both of which require other packages to run correctly. All of these packages will be installed automatically.

Depending on what packages have previously been installed in your R environment, the install of ‘tidyverse’ could be very quick or could take several minutes. As the install proceeds, messages relating to its progress will be written to the console. You will be able to see all of the packages which are actually being installed.


Installing packages using R code

If you were watching the console window when you started the install of ‘tidyverse’, you may have noticed that the line

R

install.packages("tidyverse")

was written to the console before the start of the installation messages.

You could also have installed the tidyverse packages by running this command directly in the R console. Run help(install.packages) to learn more about how to do it this way.

Because the install process accesses the CRAN repository, you will need an Internet connection to install packages.

It is also possible to install packages from other repositories, as well as Github or the local file system, but we won’t be looking at these options in this lesson.

R Resources


Learning R

  1. swirl is a package you can install in R to learn about R and data science interactively. Just type install.packages("swirl") into your R console, load the package by typing library("swirl"), and then type swirl(). Read more at swirl.

  2. Try R is a browser-based interactive tutorial developed by Code School.

  3. Anthony Damico’s twotorials are a series of 2 minute videos demonstrating several basic tasks in R.

  4. Cookbook for R by Winston Change provides solutions to common tasks and problems in analyzing data.

  5. If you’re up for a challenge, try the free R Programming MOOC in Coursera by Roger Peng.

  6. Books:

  1. Other Carpentries R lesson:


Datasets

If you need some data to play with, type data() in the console for a list of data sets. To load a dataset, type it like this: data(mtcars). Type help(mtcars) to learn more about it. You can then perform operations, e.g.

R

head(mtcars)
nrow(mtcars)
mean(mtcars$mpg)
sixCylinder <- mtcars[mtcars$cyl == 6, ]

See also rdatamining.com’s list of free datasets.


Cheat Sheets

List of R Cheat Sheets:

You can find more cheat sheets in RStudio by going to the Help panel then clicking on the Cheat Sheets dropdown menu.


Style guides

Use these resources to write cleaner code, according to established style conventions

  • Hadley Wickham’s Style Guide
  • Google’s R Style Guide
  • Tip: highlight code in your script pane and press Ctrl/Cmd + I on your keyboard to automatically fix the indents

Credit


Parts of this episode have been inspired by the following:

Key Points

  • Navigate round RStudio and create an Rproj file.
  • Use RStudio to write and run R programs.
  • Install packages using the Packages tab or the install.packages() command.