Before you start
- Nothing to install for this page: every example runs in your browser. When you want R on your own computer, see Installing R and RStudio.
- Using RStudio? Do First steps in RStudio first: the panes, saving a script, getting help, and reading errors.
- Any term new? The Glossary has it.
Learning objectives
By the end of this lesson you will be able to: assign values with the arrow; use R core data types; build and work with vectors; handle data frames; apply the main tidyverse verbs; and make a first plot with ggplot2.
Start here, even if you have never written a line of code
This lesson assumes nothing. We will explain what R even is, then build up every core idea (values, the data types, vectors, and the data frame) one small step at a time, with pictures. By the end you will understand the heart of R. Go slowly. You cannot break anything.
No R on your computer yet? Start anyway
The dark boxes marked R · runs in your browser run real R on this page. Press Run, change the code, press Run again. If you break something, press Reset. The first Run downloads R into your browser (about 20 MB, so allow up to a minute on a slow connection). Boxes on the same page share memory, so run them top to bottom. Later, type the same code into RStudio: it works the same way.
What is R, and where do I type it?
R is a programming language built for working with data and statistics: loading a table, calculating, and drawing graphs. You write R inside RStudio, a free program with two places to type: the Console (type a line, press Enter, see the answer immediately) and a Script (a saved file of lines you run when you choose, so you keep a record of what you did).
Anything after a # is a comment: a note for humans that R ignores.
[1] 4: the [1] just means "first value", so you can ignore it for now. Then change the numbers and Run again. (In RStudio, you would type the same line into the Console and press Enter.) That loop (change something, run, see the result) is how you will learn everything here.1. Storing a value: the assignment arrow
To keep a value for later, store it in a name with the assignment arrow <-. Think of the name as a labelled box. (RStudio types the arrow for you with Alt and the minus key.)
gc holds 41.5.2. The core data types
Every value in R has a type: what kind of thing it is. Three basic ones cover most of your early work. Do not memorize this; it is here to come back to.
| Type | What it is | Example |
|---|---|---|
| numeric | A number (whole or decimal). | 41.5 |
| character | Text, always written in quotes. | "TP53" |
| logical | A yes/no value: only TRUE or FALSE. | TRUE |
You usually get a logical by asking a question (a comparison): == equal, != different, > greater, < less.
One arrow or two equals?
<- stores a value in a name. == (two equals signs) asks "are these equal?" and answers TRUE or FALSE. They are different jobs.
3. Vectors: R's basic building block
R rarely deals with one value at a time. A vector is an ordered set of values of the same type, built with c() ("combine"). Almost every R operation works on a whole vector at once.
expr[1] is 12.4.R counts from 1
Unlike many languages, R numbers positions starting at 1, not 0. So expr[1] is the first value. If you have seen Python, this is the opposite, and a common thing to trip on.
4. Data frames: the spreadsheet of R
A data frame is a table: each column is a variable, each row is one observation. Gene tables, sample sheets, and clinical data all have this shape.
5. The tidyverse: five verbs that do most of the work
The tidyverse is a popular set of R packages for data work. Five verbs cover the vast majority of it. The two you will reach for first are filter (keep rows) and select (keep columns). The picture makes the difference obvious.
mutate adds a column, summarise collapses to a summary, group_by does it per group.library(tidyverse) genes |> filter(length_kb > 50) |> # keep rows where the gene is long arrange(desc(length_kb)) # sort, longest first
Try it in your browser (this box loads dplyr, the tidyverse package that provides these verbs, so the first Run takes a little longer):
The pipe |>
The pipe passes the result of one step into the next, so you read top to bottom as a sentence: "take genes, then filter, then sort." It is the backbone of tidyverse code.
6. Your first plot with ggplot2
ggplot2 builds a graph in layers: start with the data, say what goes on each axis (the aesthetics, aes), then add a geom, the kind of mark to draw.
ggplot(genes, aes(x = gene, y = length_kb)) + geom_col(fill = "#5b9cf8") + labs(title = "Gene lengths", y = "Length (kb)") + theme_minimal()
Try it in your browser (loads ggplot2 the first time, about 20 to 40 seconds). Then swap geom_col() for geom_point() and Run again:
7. Reading your own data
Real data usually arrives as a CSV file (a plain-text table with commas between the columns). Reading it is one line. To practise, we host a small table for you: practice-genes.csv (8 genes; lengths approximate, expression values made up for practice). R can read straight from a web address, so you do not need to download anything.
library(tidyverse) my_data <- read_csv("https://bionexushub.com/practice-genes.csv") glimpse(my_data) # a quick look at the columns and their types
The browser box uses read.csv(), the reader built into R, so it does not need the tidyverse. It does the same job:
Your own file
To read a file on your computer, put it in your project folder and give just its name: read_csv("my_file.csv"). First steps in RStudio shows how RStudio Projects make that "just the name" trick work.
Every key word, in plain English
- assignment arrow (<-)
- stores a value in a named box.
- numeric
- a number, whole or decimal.
- character
- text, written in quotes.
- logical
- a TRUE or FALSE value.
- vector
- an ordered set of values of the same type, made with
c(). - data frame
- a table: columns are variables, rows are observations.
- $
- pulls one column out of a data frame by name.
- tidyverse
- a set of R packages for tidy data work.
- pipe (|>)
- passes a result into the next step, read as "and then".
- filter / select
- keep certain rows / keep certain columns.
- ggplot2
- the package for building graphs in layers.
- geom
- the kind of mark a plot draws (bars, points, lines).
- comment
- a note after
#that R ignores.
Check yourself
Run each one in the box below (or in RStudio) and compare with what you should see.
| You type | You should see |
|---|---|
| mean(c(12.4, 8.1, 15.7, 3.3, 9.9)) | 9.88 |
| expr[3] | 15.7 |
| nrow(genes) | 3 (three rows) |
Practice exercises
Type each one into the scratchpad above (delete its last three lines first) or into RStudio, and run it. Peek at the solution only after you have tried.
Exercise 1: a vector and its mean. Store the numbers 5, 8, 2, 10 in a vector called counts, then get the mean.
Show a worked solution
counts <- c(5, 8, 2, 10) mean(counts) # 6.25
Exercise 2: pick one value. Using counts from Exercise 1, print the third value.
Show a worked solution
counts[3] # 2 (R counts from 1)
Exercise 3: pull out a column. Using the genes data frame from section 4, get the length_kb column and then its mean.
Show a worked solution
genes$length_kb # 19.1 81.2 188.3 mean(genes$length_kb) # 96.2
Exercise 4: keep some rows. From genes, keep only the rows on chromosome "7".
Show a worked solution
genes |> filter(chromosome == "7")
Check your understanding
|> do?$ selects a named column from a data frame (or a named element from a list).genes and want only the rows on chromosome 17. Which line is correct?filter() keeps rows by a condition, and a condition uses two equals signs (==). select() is for columns, and a single = would be an assignment.gc <- 41.5 do?<- assigns: it puts the value on the right into the name on the left.expr[1]?expr[1] is the first element.filter() and select()?Project: explore a real dataset with R →
Want more depth first? R Level 2 (Intermediate) (step 4, optional) builds straight on this.
