LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 25 lessons

Lesson 1 of 5

Module 1 · R basics

Setting up R and RStudio

Setting up R and RStudio

Setting up R and RStudio

R is a free language built for statistics, and the standard tool for analysing omics data. This lesson gets it running and has you write your first lines.

⏱ 14 min readModule 1 · R basicsFree
Lesson at a glance5 steps · about 14 min
  1. Why R
  2. Install two things
  3. The four panes
  4. Your first lines
  5. Saving values with <-

Why R

This course takes you from a first line of R to a complete analysis of real biological data: describing and testing it, drawing figures that are honest, and working through an RNA-seq experiment. Module 1, R basics, gives you the tools everything else rests on. Over five lessons you will install R, learn how it stores values, read tables from files, clean them and turn them into figures. The statistics in Module 2 then assumes you can do each of those steps without thinking about them.

R was designed by statisticians, so tests, models and plots are built in, which makes it the natural language for this course. Its other strength for biology is Bioconductor, a collection of more than 2,000 packages for genomics, used in Module 4: RNA-seq analysis.

A few terms first. A package is a bundle of extra functions, data and help pages that someone has written and shared; you add it to R when you need it. CRAN, the Comprehensive R Archive Network, is the main public store of R itself and of general-purpose packages. Bioconductor is a separate store that holds packages for biological data, for example the tools that turn RNA-seq read counts into lists of changed genes.

R is also free and open source, so anyone can read exactly what a function does, and an analysis written in R can be rerun by a colleague without buying a licence. That matters in science: a reviewer or a future student can repeat your work line by line. The usual alternative in biology is Python, which is equally good for many tasks; the habits you learn here (scripts, tidy tables, reproducible reports) carry over directly.

Two practical points follow from this. First, packages from the two stores are installed slightly differently: CRAN packages with install.packages(), which you will use below, and Bioconductor packages through a helper package called BiocManager, which you will meet in Module 4. Second, R changes over time. A new version of R is released every year, usually in spring, and packages are updated more often still. That is why a methods section should name the versions used, and why an old script can occasionally give a warning it did not give before.

R grew out of work by Ross Ihaka and Robert Gentleman, described in "R: a language for data analysis and graphics" (Journal of Computational and Graphical Statistics, 1996). Today it is maintained by the R Core Team, and the official reference is printed by citation(): R Core Team, R: A Language and Environment for Statistical Computing, R Foundation for Statistical Computing, Vienna. Bioconductor is described in Huber et al. 2015, Nature Methods. Both have home pages at r-project.org and bioconductor.org. In a methods section, give the exact R version, which R.version.string prints. Package counts grow with every release, so quote them with a year: Bioconductor held roughly 2,300 software packages in 2025.

Install two things

  1. R, the language, from CRAN at cran.r-project.org.
  2. RStudio Desktop, the program you work in, from posit.co. Install R first.

The two are separate programs that work together. R is the engine that does the calculations. RStudio is an integrated development environment (IDE): a window that gives you an editor for scripts, a place to see results, a list of your data and a help viewer, all side by side. RStudio does not contain R; it looks for an R installation on your computer when it starts, which is why R must be installed first. Posit is the company that makes RStudio.

A common first problem is installing RStudio and then wondering why nothing runs: if R is missing, RStudio cannot start a session. If that happens, install R from CRAN and restart RStudio.

If you cannot install software, create a free Posit Cloud account and start an RStudio project in your browser. Everything in this course works there.

Then install the packages this course uses. You only do this once; each script then loads them with library().

R · run once
install.packages(c("dplyr", "tidyr", "ggplot2", "pheatmap"))

What this does

  • c("dplyr", "tidyr", "ggplot2", "pheatmap") combines four package names into one list of text values. The quotes tell R these are names, not objects it should look up.
  • install.packages() downloads each named package from CRAN, together with any other packages it depends on, and stores them in your R library, a folder on your computer.
  • The four packages are dplyr (filtering, changing and summarising tables), tidyr (reshaping tables), ggplot2 (figures) and pheatmap (heatmaps). You will use each of them in this module.

R prints progress messages while it downloads. Messages are normal; a line containing the word error is the one to read carefully. The difference between installing and loading is worth fixing in your mind now: install.packages() is like buying a book and putting it on your shelf, once per computer; library() takes it off the shelf, once per R session. A script should contain library() lines, but not install.packages() lines that would reinstall everything each time it runs.

To check that the installation worked, run library(ggplot2) in the Console. If R returns to the prompt with no error, the package is ready. An error such as "there is no package called 'ggplot2'" means the download failed or the name was mistyped; package names are case-sensitive, so GGplot2 will not be found.

Two questions sometimes appear during installation. R may ask you to choose a mirror, a copy of CRAN on a server near you; any of them will do. On Windows and macOS it may also ask whether to install a newer version "from sources", which means building the package from its code on your own computer. Answering no is the safe choice: you get the slightly older ready-built version, which is all this course needs. Finally, packages belong to one R installation. After you upgrade R to a new major version you may need to run install.packages() again.

The four panes

Source
  • Top left. Scripts: code you want to keep.
  • Run the current line with Ctrl+Enter (Cmd+Enter on a Mac).
Console
  • Bottom left. Where code runs and results appear.
  • Good for quick checks you will not keep.
Environment
  • Top right. Every object you have created.
  • Click a table to view it like a spreadsheet.
Files, Plots, Help
  • Bottom right. Folders, figures and the manual.
  • Type ?mean for help on any function.
Setting up R and RStudio · LSMA free course An RStudio window divided into four panes: Source with a script at top left, Console with results at bottom left, Environment listing objects at top right, and Files, Plots and Help at bottom right. RStudio SOURCE · SCRIPT # sequencing depth reads <- 900000000 coverage <- reads * … Ctrl+Enter sends a line down CONSOLE · RESULTS > round(coverage, 1) [1] 43.5 > ENVIRONMENT · OBJECTS coverage genome_size read_length reads FILES · PLOTS · HELP Files Plots Help ?mean opens the manual page
Code you want to keep lives in a script in the Source pane (top left); when you run a line it is sent to the Console (bottom left), where the result appears. Every object you create is listed in the Environment pane (top right). Schematic, not to scale.

The layout above is RStudio's default; you can rearrange the panes in its settings, but the four jobs stay the same. The most useful habit is to type in the Source pane, not the Console. Code typed in the Console runs once and is gone; code in a script can be saved, corrected and run again. When you press Ctrl+Enter (Cmd+Enter on a Mac) in a script, RStudio copies the current line to the Console and runs it there, so you see both the command and its result.

To run several lines at once, select them and press Ctrl+Enter; to run the whole script, use Ctrl+Shift+Enter (Cmd+Shift+Enter on a Mac). Running the whole script from the top is the real test of an analysis, because it shows whether the code works in order without anything you typed by hand along the way.

One setting is worth changing on day one. By default RStudio offers to save your objects to a file called .RData when you quit and loads them again next time. That sounds helpful, but it means objects can survive from an old session even after you have deleted the code that made them, and a script can then seem to work when it would fail on a fresh start. In Tools › Global Options › General, untick "Restore .RData into workspace at startup" and set "Save workspace to .RData on exit" to Never. Your script, not the saved workspace, is then the record of your work. Session › Restart R gives you a clean session whenever you want to check.

The Environment pane is also a quick way to spot mistakes. If an object you expected is missing, the line that creates it did not run; if a table has fewer rows than you expected, something earlier removed them.

Your first lines

Type these into the console and press Enter after each. R works as a calculator.

When R is ready for input, the Console shows a > sign, called the prompt. If you see a + instead, R thinks your command is unfinished, often because a bracket or quote has not been closed. Press Esc to cancel and type the line again.

R
2 + 3
10 / 4
sqrt(16)
log2(8)
[1] 5 [1] 2.5 [1] 4 [1] 3

What this does

  • 2 + 3 and 10 / 4 use R's arithmetic operators: +, -, * for multiply and / for divide. R follows the usual order of operations, so multiplication and division happen before addition and subtraction unless you use brackets.
  • sqrt(16) is your first function: a named command followed by round brackets that hold its input. sqrt() returns the square root, and 4 × 4 = 16, so the answer is 4.
  • log2(8) is the logarithm to base 2: the power you must raise 2 to in order to get 8. Because 2 × 2 × 2 = 8, that power is 3.

Reading the output. Each answer appears on its own line, in the same order as the commands: 5, 2.5, 4 and 3. Note that 10 / 4 gives 2.5, not 2; R does not round division unless you ask it to.

Base-2 logarithms appear all through omics. A gene whose expression doubles has a log2 change of 1, one that quadruples has a change of 2, and one that halves has a change of −1. Working on this scale makes increases and decreases of the same size look symmetrical. Be careful with the plain log() function: in R it uses base e (the natural logarithm), not base 10 or base 2, which is a common source of confusion.

The value inside a function's brackets is called an argument. Many functions take more than one, separated by commas, and each has a name. log(8, base = 2) gives the same answer as log2(8), and log10(100) gives 2. When you are unsure what arguments a function takes, type ?log and read the Usage and Arguments sections of the help page.

You will also see your first error messages here. If you type sqrt("16"), with quotes, R replies with an error saying the argument is non-numeric: the quotes made 16 a piece of text, and you cannot take the square root of text. Errors are R telling you exactly which command failed and, usually, why. Read the message before changing anything; it is often more specific than it first looks.

The [1] means “this is the first value of the answer”. You will see why in Vectors, functions and loops.

Go deeper: why 0.1 + 0.2 is not quite 0.3

Computers store most numbers in binary, base 2, with a fixed number of digits. Many tidy decimals, such as 0.1, have no exact binary form, just as 1/3 has no exact decimal form. R stores the nearest value it can, so tiny rounding errors creep in. Type 0.1 + 0.2 == 0.3 and R answers FALSE, although both sides print as 0.3.

The error is about 2 parts in 10 to the power 16, far too small to matter in biology. It does matter when you test for exact equality with ==. Use isTRUE(all.equal(0.1 + 0.2, 0.3)) instead: all.equal() allows a tiny tolerance and gives TRUE. Whole numbers up to about 9 × 10 to the power 15 are stored exactly, so counts of reads never suffer from this.

Saving values with <-

The arrow <- stores a value under a name, called an object. Read it as “gets”.

So reads <- 900000000 reads as "reads gets nine hundred million". Storing a value prints nothing; R quietly files it away and lists it in the Environment pane. You see a value only when you type the object's name on its own. In RStudio, Alt+minus (Option+minus on a Mac) types the arrow for you.

R
# sequencing depth for a whole genome
reads       <- 900000000
read_length <- 150
genome_size <- 3.1e9          # 3.1e9 means 3.1 × 10^9

coverage <- reads * read_length / genome_size
coverage
round(coverage, 1)
[1] 43.54839 [1] 43.5

What this does, line by line

  1. The first line starts with #, so it is a comment: a label for the reader that R skips.
  2. reads <- 900000000 stores the number of reads, 900 million.
  3. read_length <- 150 stores the length of each read, 150 bases. The extra spaces before the arrow only line the code up; R ignores them.
  4. genome_size <- 3.1e9 stores the genome size in scientific notation: e9 means "times 10 to the power 9", so 3.1e9 is 3,100,000,000. It saves typing nine zeros and miscounting them.
  5. coverage <- reads * read_length / genome_size multiplies the number of reads by their length to get the total bases sequenced, then divides by the genome size. The result is stored in a new object, coverage.
  6. coverage on its own asks R to print the stored value.
  7. round(coverage, 1) rounds it to one decimal place. The second argument, 1, says how many decimal places to keep. The stored value itself is not changed.

Reading the output. The first line, 43.54839, is the full value as R prints it by default (seven significant digits). The second, 43.5, is the rounded version. Both mean the same thing: each base of the genome was read about 44 times on average.

Object names are case-sensitive, so Reads and reads are two different objects. Names cannot start with a number or contain spaces, which is why this code uses underscores, as in read_length. Choose names that say what the value is; genome_size is far easier to check next month than g.

Objects are what make a script reusable. Suppose the next run produced 600 million reads instead. You change the first line to reads <- 600000000, rerun the script, and coverage is recalculated from the new value (about 29). Assigning to a name that already exists replaces the old value without any warning, so a name should always mean one thing in a script; reusing coverage for a different quantity later on is an easy way to confuse yourself.

The calculation itself is the average depth. In real data, coverage is uneven: some regions, such as those very rich in G and C bases, are read far fewer times than others, so an average of 44 does not mean every base was read 44 times. You may also see = used instead of <- in other people's code. Both store a value, but this course uses the arrow throughout, as most R style guides do.

Lines starting with # are comments: notes R ignores. Write your code in a script (File › New File › R Script) and save it with a .R ending, so you can run the whole analysis again later.

A script is a plain text file containing your commands in order. If you find a mistake in step 2, you correct that line and rerun the script, and every later step updates with it. Working in the Console alone gives you no such record. A good script also starts with a few comment lines saying what it does, which data it uses, and who wrote it.

Key point

Create an RStudio Project (File › New Project) for this course and save the course files in its folder. They are listed on the course overview, under What you need, and the course files. R then finds files by name, and everything stays together.

Opening a Project sets R's working directory, the folder R looks in when you give a file name without a full path. Without one, a script that works on your laptop may fail on a colleague's, because C:/Users/you/Desktop/… does not exist there. With a Project, a line such as read.csv("airway_samples.csv") in Data frames and files works wherever the project folder is copied.

Further reading · Module 1R for Data Science, 2nd edition: the free book that covers this module and much more. · All reading for this course

Check your understanding

1. What does x <- 5 do?

2. What does log2(16) return?

3. Where should you write code you want to run again next week?

Up next

Lesson 2

Vectors, functions and loops

Ask BioTutor

Create a free website with Framer, the website builder loved by startups, designers and agencies.