Lesson 2 of 14 · 11 min
Vectors and Data Types
In R, almost everything you touch is stored in a vector — an ordered collection of values that are all the same type. A single gene name, a list of expression measurements, or one column from a spreadsheet can all be stored as vectors. Learning to build and inspect vectors is the foundation for every table and analysis you will write later.
# a numeric vector: five gene-expression values
# (TPM = transcripts per million, a common RNA-seq unit)
expr <- c(12.5, 8.3, 15.1, 0.0, 9.7)
expr
class(expr)
length(expr)[1] 12.5 8.3 15.1 0.0 9.7
[1] "numeric"
[1] 5
The arrow <- is R's assignment operator: it stores whatever is on the right into the name on the left, so expr now refers to your vector. The function c(), short for combine, glues the separate numbers into a single vector. Here class() reports that the values are numeric (ordinary numbers), length() counts how many there are, and the [1] at the start of a printed line simply labels the position of the first value shown on that line.
Text, logicals, and factors
genes <- c("TP53", "BRCA1", "EGFR")
expressed <- c(TRUE, FALSE, TRUE)
condition <- factor(c("tumor", "normal", "tumor"))
class(genes)
class(expressed)
class(condition)
levels(condition)[1] "character"
[1] "logical"
[1] "factor"
[1] "normal" "tumor"
A character vector holds text, so every value must sit inside quotes, like the gene symbols above. A logical vector holds only TRUE or FALSE, which R uses to answer yes/no questions and to filter data. A factor stores categories: it looks like text, but R remembers the distinct labels as its levels (here normal and tumor, listed in alphabetical order), which is exactly how experimental groups are represented for statistics.
expr[1] # the first value (R counts from 1, not 0)
expr[c(1, 3)] # the first and third values
expr * 2 # vectorisation: every element is doubled at once
expr[4] <- NA # NA marks a missing or unknown value
mean(expr) # one NA makes the whole result NA
mean(expr, na.rm = TRUE) # na.rm = TRUE skips the missing value
even <- seq(2, 10, by = 2) # seq() builds a regular sequence
even[1] 12.5
[1] 12.5 15.1
[1] 25.0 16.6 30.2 0.0 19.4
[1] NA
[1] 11.4
[1] 2 4 6 8 10
Tip: expr * 2 is an example of vectorisation — R applies the operation to every element at once, with no loop required, which keeps your code short and fast. Be careful with NA: any arithmetic that includes a missing value returns NA, so add na.rm = TRUE when you want R to ignore the gaps. Note that expr * 2 is computed before expr[4] is set to NA, so it still doubles the original five values.
Try it yourself: Build a numeric vector with heights <- c(1.62, 1.78, NA, 1.55), the heights of four plants in metres. Check it with length(heights) and class(heights), pull out the second plant with heights[2], and average the measured plants using mean(heights, na.rm = TRUE). Finally run heights * 100 to convert every height to centimetres in a single vectorised step.